我正在编写一个小型应用程序,以在社交网络上执行自动发布。
我的意图是,用户可以通过Web界面在特定时间创建帖子,而bot可以检查预定的新帖子并执行。
我在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")
}
}
答案 0 :(得分:1)
在彼得的回应下,我能够适应所有需要以组装草图。
我不知道这是否是最好的方法,也许某些功能会不必要地消耗处理资源。如果有人对重构有更好的想法,我将不胜感激。
c