这个小玩意儿适用于让服务器做一些自动的东西,比如定时查库发送报表、定时让爬虫爬数据、定时提醒等等。
为啥不用自己电脑直接运行?-----------因为自己电脑不能24小时开机,一旦关机就触发不了了,所以就要服务器帮忙啦。
1、写一个用于触发器python文件:t_apscheduler.py
这个文件有两个作用:
1.1、用APScheduler写触发器(date定时执行;interval间隔调度;cron特定时间周期触发)
1.2、写一个函数,这个函数用os.system写要执行的py脚本
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime, date
def execute():
os.system('python t_datetime.py')
scheduler = BlockingScheduler()
# 在某个时间点执行一次
# scheduler.add_job(execute, 'date', run_date=datetime(2022, 3, 16, 17, 13, 30))
# 每隔N时间执行一次。为了演示的更直观,就用这个每隔两秒运行一次
scheduler.add_job(execute, 'interval', seconds=2)
# 特定时间内,周期性触发
# scheduler.add_job(execute, 'cron', day_of_week='0-6', hour=17, minute=21)
scheduler.start()
1.3、随意写一个要执行的py:t_datetime.py
import datetime
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("now", now)
2、把要执行的py(t_datetime.py)和这个触发器py(t_apscheduler.py),都放在服务器上。(注意服务器先安装好APScheduler包:pip3 install apscheduler)
pip3 install apscheduler
3、执行命令:nohup python t_apscheduler.py &
用tail -f nohup.out ,就可以看到要执行的py文件执行情况了。
执行成功,没报错。目标完成!
参考资料:nohup的用法:
Linux nohup 命令 | 菜鸟教程 (runoob.com)
定时任务框架APScheduler:
Python 定时任务的实现方式 | lizhen's blog (lz5z.com)



