【问题标题】:How to make this script loop every hour如何让这个脚本每小时循环一次
【发布时间】:2020-09-04 11:12:58
【问题描述】:

我正在创建一个机器人,它每 60 分钟发布一次 covid 号码,我已经完成了,但不知道如何让它重复。任何想法?这是我心中的一个小项目,也是我要做的最后一件事。 (如果您在解决方案中回答出版物中的代码,那将非常酷)

import sys
CONSUMER_KEY = 'XXXX'
CONSUMER_SECRET = 'XXXX'
ACCESS_TOKEN = 'XXXX'
ACCESS_TOKEN_SECRET = 'XXXX'
import tweepy

import requests
from lxml import html


def create_tweet():
    response = requests.get('https://www.worldometers.info/coronavirus/')
    doc = html.fromstring(response.content)
    total, deaths, recovered = doc.xpath('//div[@class="maincounter-number"]/span/text()')

    tweet = f'''Coronavirus Latest Updates
Total cases: {total}
Recovered: {recovered}
Deaths: {deaths}

Source: https://www.worldometers.info/coronavirus/

#coronavirus #covid19 #coronavirusnews #coronavirusupdates #COVID19
'''
    return tweet


if __name__ == '__main__':
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

    # Create API object
    api = tweepy.API(auth)

    try:
        api.verify_credentials()
        print('Authentication Successful')
    except:
        print('Error while authenticating API')
        sys.exit(5)

    tweet = create_tweet()
    api.update_status(tweet)
    print('Tweet successful')

【问题讨论】:

标签: python html loops web twitter


【解决方案1】:

您可以在代码末尾简单地添加此语句

sleep(3600)

如果你想让它无休止地运行,你可以这样做:

while True:
    insert your main code here
    sleep(3600)

【讨论】:

  • idk 为什么当我像你说的那样添加它时它会崩溃。
  • 哦对,你要导入时间库。 from time import * 或者只是from time import sleep
【解决方案2】:

您可能想要使用调度程序,Python 中已经有一个内置调度程序 (sched),请在此处阅读更多信息:https://docs.python.org/3/library/sched.html

【讨论】:

    【解决方案3】:

    您必须使用如下所示的计时器。 (函数refresh每小时引用一次自己)

    from threading import Timer
    
    def refresh(delay_repeat=3600): # 3600 sec for one hour
        # Your refresh script here
        # ....
        # timer
        Timer(delay_repeat, refresh, (delay_repeat, )).start()
    

    在此处查看我的可运行刷新图以了解想法: How can I dynamically update my matplotlib figure as the data file changes?

    【讨论】:

    • idk 为什么我像你说的那样添加它时它会崩溃。
    • 您的应用程序中有 GUI 吗?您应该通过发布事件而不强制刷新来对 GUI 执行刷新操作
    【解决方案4】:

    您可以在 Python 中使用任务调度程序。 “schedule”是 python 中的一个库,您可以使用 pip 或 conda 安装它。该库允许您在给定的时间间隔(每天、每周每小时等)后重新运行函数。

    首先你需要使用 pip 安装库

    pip install schedule
    

    其次,将代码放入函数中。例如:

    def theCode():
        print("Do Something")
    

    三、设置时间表:

    schedule.every(2).hours.do(theCode)
    while 1:
        schedule.run_pending()
        time.sleep(10)
    

    【讨论】:

      猜你喜欢
      • 2012-04-06
      • 2019-03-13
      • 2022-12-18
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-31
      相关资源
      最近更新 更多