【问题标题】:How to run a python script at a specific time(s)如何在特定时间运行 python 脚本
【发布时间】:2011-04-15 13:57:57
【问题描述】:

我想编写一个简单的 python 脚本来完成特定的工作。我正在从网站获取一些时间和链接信息。

times=
[
('17.04.2011', '06:41:44', 'abc.php?xxx'),
('17.04.2011', '07:21:31', 'abc.php?yyy'),
('17.04.2011', '07:33:04', 'abc.php?zzz'),
('17.04.2011', '07:41:23', 'abc.php?www'),]

在正确的时间点击这些链接的最佳方式是什么?我是否需要计算当前和列表中的一个之间的时间间隔并休眠一段时间?

我真的被困在这一点上,并对任何可能有用的想法持开放态度。

【问题讨论】:

标签: python


【解决方案1】:

看看 Python 的 sched 模块。

【讨论】:

    【解决方案2】:

    您可以使用日程安排模块,它易于使用,可以满足您的要求。

    你可以试试这样的。

    import datetime, schedule, request
    
    TIME = [('17.04.2011', '06:41:44', 'abc.php?xxx'),
        ('17.04.2011', '07:21:31', 'abc.php?yyy'),
        ('17.04.2011', '07:33:04', 'abc.php?zzz'),
        ('17.04.2011', '07:41:23', 'abc.php?www')]
    
    def job():
        global TIME
        date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
        for i in TIME:
            runTime = i[0] + " " + i[1]
            if i and date == str(runTime):
                request.get(str(i[2]))
    
    schedule.every(0.01).minutes.do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)
    

    我已经使用 request 模块和 get 方法来调用这些 URL。您可以编写任何适合您的方法。

    【讨论】:

    • 这是一个很好的例子!
    【解决方案3】:

    这可能会有所帮助:How do I get a Cron like scheduler in Python? 这是关于 Python 中类似 cron 的调度。是的,它基于睡眠。

    【讨论】:

      【解决方案4】:

      我终于制作并使用了这个。

      def sleep_till_future(f_minute):
          """
              The function takes the current time, and calculates for how many seconds should sleep until a user provided minute in the future.
          """
          import time,datetime
      
      
          t = datetime.datetime.today()
          future = datetime.datetime(t.year,t.month,t.day,t.hour,f_minute)
      
          if future.minute <= t.minute:
              print("ERROR! Enter a valid minute in the future.")
          else:
              print "Current time: " + str(t.hour)+":"+str(t.minute)
              print "Sleep until : " + str(future.hour)+":"+str(future.minute)
      
              seconds_till_future = (future-t).seconds
              time.sleep( seconds_till_future )
              print "I slept for "+str(seconds_till_future)+" seconds!"
      

      【讨论】:

        猜你喜欢
        • 2013-11-27
        • 2015-11-08
        • 2020-11-08
        • 1970-01-01
        • 1970-01-01
        • 2017-09-25
        • 2019-04-18
        • 2020-10-24
        • 2020-11-01
        相关资源
        最近更新 更多