【问题标题】:python how to run a function everyday at specific time, but can also be terminatedpython如何每天在特定时间运行一个函数,但也可以终止
【发布时间】:2018-02-17 03:37:12
【问题描述】:

我是新来探索如何在 python 中做到这一点。我想做的是在每个工作日的特定时间运行一个函数,例如,在 14:55,就在中国股市收盘前 5 分钟。此函数将从股票市场数据馈送 API 中提取一些数据并进行一些简单的计算以生成信号(-1 表示做空,+1 表示做多,0 表示不做任何事情)。我现在还没有发出进行交易的信号。我只是每天将信号保存到本地文件中。因此,我可能能够在 2 周内或任何我想停止此调度程序的时间收集信号。

我注意到APScheduler 模块经常被推荐。但我试过了,没有找到让调度程序在 2 周后停止运行的方法。我只找到了设置调度程序运行的方法,可能每 10 分钟运行一次,但它只会每 10 分钟运行一次指定的函数,并且不能以编程方式停止,只能通过按 Ctrl+C?例如,我想每 10 分钟运行一次函数 6 次,在 APScheduler 中,无论如何我都没有看到指定 '6 times' 参数。或者我想每 10 分钟运行一次函数,直到 1 小时后。我也没有看到“1 小时后”或“16:30”的说法。怎么做?

目前,我正在这样做:

def test_timer():
    '''
    Uses datetime module.
    '''
    running = 1
    stop_time = datetime.now() + timedelta(seconds=60)
    while running:

        print('I\'m working...')
        time.sleep(5)
        running = datetime.now() < stop_time

    print('Goodbye!')

已编辑:我在 Windows 10 中使用 python 3.6。

【问题讨论】:

  • 如果您使用的是 linux,一个简单的方法是使用 crontab,它会在您需要时运行您的代码
  • @Squick Lol 问题从不包含OS 定义
  • @dsgdfg 这就是我说“如果”的原因
  • 你是对的,但我说的是@StayFoolish
  • 我不熟悉高级 Python 调度程序。但是:在他们的文档中(apscheduler.readthedocs.io/en/latest/)I 发现:APScheduler 具有三个可以使用的内置调度系统: - Cron 式调度(具有可选的开始/结束时间) - 基于间隔的执行(以均匀的间隔运行作业,可选开始/结束时间)-一次性延迟执行(在设定的日期/时间运行一次作业)所以它提供停止时间,不是吗?

标签: python timer scheduled-tasks scheduler


【解决方案1】:

试试这个例子

from datetime import datetime

from apscheduler.schedulers.background import BackgroundScheduler


def job_function():
    print("Hello World")

sched = BackgroundScheduler()

# Schedule job_function to be called every 1 second
# FIXME: Do not forget to change end_date to actual date
sched.add_job(job_function, 'interval', seconds=1, end_date="2017-09-08 12:22:20")

sched.start()

更新 #1

from apscheduler.schedulers.background import BackgroundScheduler

def job_function():
    print("Hello World")

# Here, you can generate your needed days
dates = ["2017-09-08 13:30:20", "2017-09-08 13:31:20", "2017-09-08 13:32:20"]
sched = BackgroundScheduler()                      

for date in dates:
    sched.add_job(job_function, "date", next_run_time=date)

sched.start()

【讨论】:

  • 谢谢,我没有注意到我可以添加 end_date 参数。有没有办法指定调度程序在每个工作日运行?或者跑 9 次。
【解决方案2】:

Linux 中的 crontab 或 Windows 中的任务计划程序似乎存在问题。

【讨论】:

猜你喜欢
  • 2020-01-13
  • 2020-11-23
  • 2017-09-25
  • 2019-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-14
  • 2021-04-05
相关资源
最近更新 更多