草庐IT

go - 有什么更好的方法来实现在社交网络中验证和执行帖子的例程?

coder 2023-06-30 原文

我正在编写一个小应用程序来在社交网络上执行自动发帖。

我的意图是用户可以通过网络界面在特定时间创建帖子,机器人可以检查计划的新帖子并执行它们。

我在使用 Go 上的例程和 channel 时遇到问题。

我将在下面留下一个反射(reflect)我的代码实际情况的示例。它包含一些注释以使其更易于理解。

实现随时检查新帖子的例程的最佳方法是什么? 记住:

  1. 用户可以随时输入新帖子。
  2. 该机器人可以同时管理数百/数千个帐户。消耗尽可能少的处理能力至关重要。

play.golang.org (here)


    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")
        }

    }

最佳答案

有了 Peter 的回应,我能够适应所有需要来组合草图。

我不知道这是否是最好的方法,也许某些功能会不必要地消耗处理资源。如果有人有更好的重构想法,我将不胜感激。


    package main

    import (
        "fmt"
        "log"
        "net/http"
        "sort"
        "time"
    )

    type posting struct {
        caption string
        scheduledTo time.Time
    }

    const dateLayoutFormat  = "02-01-2006 15:04:05"

    var botStatus = true
    var indexPosting int
    var tickerSchedule = time.NewTicker(1)
    var posts = []posting{
        {caption: "item 1", scheduledTo: time.Now().Add(5 * time.Second)},
        {caption: "item 2", scheduledTo: time.Now().Add(25 * time.Second)},
    }

    func init() {
        indexPosting = len(posts)
    }

    func main() {
        http.HandleFunc("/", func (w http.ResponseWriter, r *http.Request) {
            fmt.Fprint(w, "Bem vindo ao bot")
        })

        http.HandleFunc("/stop", func (w http.ResponseWriter, r *http.Request) {
            fmt.Fprint(w, "Parando o bot!")
            stopBot()
        })

        http.HandleFunc("/start", func (w http.ResponseWriter, r *http.Request) {
            fmt.Fprint(w, "Iniciando o bot!")
            startBot()
        })

        http.HandleFunc("/add", func (w http.ResponseWriter, r *http.Request) {
            t := time.Now().Add(5 * time.Second)
            indexPosting++

            addItemDB(posting{
                caption: fmt.Sprint("item ", indexPosting),
                scheduledTo: t,
            })

            fmt.Fprint(w, "Adicionando nova postagem \nPróximo post será: ", t.Format(dateLayoutFormat))
        })

        if botStatus {
            go workerScheduled()
        }

        log.Print("Inicnando server...")
        if err := http.ListenAndServe(":9090", nil); err != nil {
            log.Print("erro ao iniciar servidor => ", err)
        }

    }

    func workerScheduled() {
        for {
            log.Print("listando as próximas postagens")

            pts := getNextPostsDB()
            if len(pts) == 0 {
                log.Print("sem postagem agendada")
                botStatus = false
                return
            }

            p1 := pts[0]

            log.Printf("Próxima postagem será: %s \n\n", string(p1.scheduledTo.Format(dateLayoutFormat)))
            <- updateTimer(p1.scheduledTo).C

            if !botStatus {
                log.Print("postagem cancelado, bot status = parado")
                return
            }

            if time.Until(p1.scheduledTo) > 1 * time.Second {
                updateTimer(p1.scheduledTo)
                log.Print("timer resetado")
                continue
            }

            post(p1)
            if len(pts) > 1 {
                p2 := pts[1]
                updateTimer(p2.scheduledTo)
            }
            updatePostedDB()
        }
    }

    func updateTimer(t time.Time) *time.Ticker {
        tickerSchedule = time.NewTicker(t.Sub(time.Now()))
        return tickerSchedule
    }

    func post(p posting) {
        log.Printf("'%s' postado com sucesso", p.caption)
    }

    func addItemDB(p posting) {
        posts = append(posts, p)
        if botStatus {
            next := getNextPostDB()
            updateTimer(next.scheduledTo)
        } else {
            botStatus = true
            go workerScheduled()
        }
    }

    func getNextPostDB() posting {
        return getNextPostsDB()[0]
    }

    func getNextPostsDB() []posting {
        orderPostsList()
        removePostExpired()
        return posts
    }

    func removePostExpired() {
        for _, p := range posts {
            if p.scheduledTo.Before(time.Now()) {
                log.Printf("removendo postagem expirada")
                removePostByIndex(getIndexOf(p))
            }
        }
    }

    func removePostByIndex(i int) {
        copy(posts[i:], posts[i+1:])
        posts = posts[:len(posts)-1]
    }

    func getIndexOf(post posting) int {
        for i, p := range posts {
            if p.caption == post.caption {
                return i
            }
        }
        return -1
    }

    func updatePostedDB() {
        removePostByIndex(0)
    }

    func orderPostsList() {
        sort.Slice(posts, func(i, j int) bool {
            return posts[i].scheduledTo.Before(posts[j].scheduledTo)
        })
    }

    func startBot() {
        if !botStatus {
            log.Printf("comando 'iniciar bot'")
            botStatus = true
            go workerScheduled()
        } else {
            log.Printf("comando 'iniciar bot' (já iniciado)")
        }
    }

    func stopBot() {
        if botStatus {
            log.Printf("comando 'pausar bot'")
            botStatus = false
            tickerSchedule.Stop()
        } else {
            log.Printf("comando 'pausar bot' (já pausado)")
        }
    }

关于go - 有什么更好的方法来实现在社交网络中验证和执行帖子的例程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54117528/

有关go - 有什么更好的方法来实现在社交网络中验证和执行帖子的例程?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-on-rails - Rails - 子类化模型的设计模式是什么? - 2

    我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co

  6. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  7. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  8. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  9. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  10. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

随机推荐