Home >Backend Development >Python Tutorial >Python implements scheduled tasks
This article mainly introduces Python to implement scheduled tasks. There are mainly 5 methods, which have certain reference value. Interested friends can refer to them.
There are many ways to implement scheduled tasks in Python. Here are several
loop sleeps:
This is the simplest way, put the information to be executed in the loop task, and then sleep for a while before executing it. The disadvantage is that it is not easy to control, and sleep is a blocking function.
def timer(n): ''''' 每n秒执行一次 ''' while True: print time.strftime('%Y-%m-%d %X',time.localtime()) yourTask() # 此处为要执行的任务 time.sleep(n)
Threading’s Timer:
The Timer in the threading module can Helps implement scheduled tasks and is non-blocking.
For example, print helloworld after 3 seconds:
def printHello(): print "hello world" Timer(3, printHello).start()
For example, print helloworld every 3 seconds:
def printHello(): print "Hello World" t = Timer(2, printHello) t.start() if __name__ == "__main__": printHello()
Use the sched module:
sched is a kind of scheduling (delay processing mechanism).
# -*- coding:utf-8 -*- # use sched to timing import time import os import sched # 初始化sched模块的scheduler类 # 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。 schedule = sched.scheduler(time.time, time.sleep) # 被周期性调度触发的函数 def execute_command(cmd, inc): ''''' 终端上显示当前计算机的连接情况 ''' os.system(cmd) schedule.enter(inc, 0, execute_command, (cmd, inc)) def main(cmd, inc=60): # enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数, # 给该触发函数的参数(tuple形式) schedule.enter(0, 0, execute_command, (cmd, inc)) schedule.run() # 每60秒查看下网络连接情况 if __name__ == '__main__': main("netstat -an", 60)
Use the timing framework APScheduler:
APScheduler is based on Quartz A Python scheduled task framework. Provides tasks based on date, fixed time interval and crontab type, and can persist tasks.
I haven’t tried this myself yet, I will add more after I have used it for a while.
Use Windows scheduled tasks:
Here you can package the required Python program into an exe file, and then run it under Windows Set up scheduled execution.
The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support the PHP Chinese website.
For more articles related to Python's implementation of scheduled tasks, please pay attention to the PHP Chinese website!