ソーシャル ネットワークで自動投稿を実行する小さなアプリケーションを作成しています。
私の意図は、ユーザーが Web インターフェイスを介して特定の時間に投稿を作成し、ボットがスケジュールされた新しい投稿をチェックして実行できるようにすることです。
Go でルーティンとチャンネルを操作するのに問題があります。
私のコードの現実を反映する例を以下に残します。理解しやすいように、いくつかのコメントが含まれています。
いつでも新しい投稿をチェックするルーチンを実装する最良の方法は何ですか? 記憶:
- ユーザーはいつでも新しい投稿を入力できます。
- ボットは、数百または数千のアカウントを同時に管理できます。消費する処理をできるだけ少なくすることが不可欠です。
package main
import (
"fmt"
"sync"
"time"
)
var botRunning = true
var wg = &sync.WaitGroup{}
func main() {
// I start the routine of checking for and posting scheduled appointments.
wg.Add(1)
go postingScheduled()
// Later the user passes the command to stop the post.
// At that moment I would like to stop the routine immediately without getting stuck in a loop.
// What is the best way to do this?
time.Sleep(3 * time.Second)
botRunning = false
// ignore down
time.Sleep(2 * time.Second)
panic("")
wg.Wait()
}
// Function that keeps checking whether the routine should continue or not.
// Check every 2 seconds.
// I think this is very wrong because it consumes unnecessary resources.
// -> Is there another way to do this?
func checkRunning() {
for {
fmt.Println("Pause/Running? - ", botRunning)
if botRunning {
break
}
time.Sleep(2 * time.Second)
}
}
// Routine that looks for the scheduled posts in the database.
// It inserts the date of the posts in the Ticker and when the time comes the posting takes place.
// This application will have hundreds of social network accounts and each will have its own function running in parallel.
// -> What better way to check constantly if there are scheduled items in the database consuming the least resources on the machine?
// -> Another important question. User can schedule posts to the database at any time. How do I check for new posts schedule while the Ticker is waiting for the time the last posting loaded?
func postingScheduled() {
fmt.Println("Init bot posting routine")
defer wg.Done()
for {
checkRunning()
<-time.NewTicker(2 * time.Second).C
fmt.Println("posted success")
}
}