← Back to all posts
Secure Development2 min read

Executing Scheduled Tasks in Python

Use Python’s built-in and third-party libraries to run scheduled tasks, pass arguments, and execute tasks concurrently with threading.

Read in Chinese→

Executing Scheduled Tasks in Python

Use Python’s built-in and third-party libraries to run scheduled tasks.

Using the sched Module

sched is essentially used to execute delayed tasks.
schedule is a simple and straightforward third-party scheduling library that must first be installed with pip.
Here is a good example:

import schedule
import time

# 定义你要周期运行的函数
def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)               # 每隔 10 分钟运行一次 job 函数
schedule.every().hour.do(job)                    # 每隔 1 小时运行一次 job 函数
schedule.every().day.at("10:30").do(job)         # 每天在 10:30 时间点运行 job 函数
schedule.every().monday.do(job)                  # 每周一 运行一次 job 函数
schedule.every().wednesday.at("13:15").do(job)   # 每周三 13:15 时间点运行 job 函数
schedule.every().minute.at(":17").do(job)        # 每分钟的 17 秒时间点运行 job 函数

while True:
    schedule.run_pending()   # 运行所有可以运行的任务
    time.sleep(1)

Passing Arguments

import schedule
import time

# 定义你要周期运行的函数
def job(msg):
    print("I'm working...")
    print('接受参数为:{}'.format(msg))

schedule.every(10).seconds.do(job,msg='10s')

while True:
    schedule.run_pending()   # 运行所有可以运行的任务
    time.sleep(1)

Executing Concurrent Tasks

import schedule,time
def job1(msg):
    time.sleep(1)
    print('任务1接受参数为:{}'.format(msg))
def job2(msg):
    time.sleep(2)
    print('任务2接受参数为:{}'.format(msg))
def job3(msg):
    time.sleep(3)
    print('任务3接受参数为:{}'.format(msg))
schedule.every(1).seconds.do(job1,msg='任务1')
schedule.every(3).seconds.do(job2,msg='任务2')
schedule.every(1).seconds.do(job3,msg='任务3')
while 1:
    schedule.run_pending()
```In practice, the tasks should execute sequentially.  
![在这里插入图片描述](/images/20200207104831217.png)

Use `threading` to enable concurrency.  
![在这里插入图片描述](/images/20200207104939256.png)```python
# -*- coding:utf-8 -*-
import schedule,time
import threading

def job1(msg):
    time.sleep(1)
    print('任务1接受参数为:{}'.format(msg))
def job2(msg):
    time.sleep(2)
    print('任务2接受参数为:{}'.format(msg))
def job3(msg):
    time.sleep(3)
    print('任务3接受参数为:{}'.format(msg))
def ensure_schedule_1():
    threading.Thread(target=job1,args=(1,)).start()
def ensure_schedule_2():
    threading.Thread(target=job2,args=(2,)).start()
def ensure_schedule_3():
    threading.Thread(target=job3,args=(3,)).start()
def run():
    schedule.every(1).seconds.do(ensure_schedule_1)
    schedule.every(1).seconds.do(ensure_schedule_2)
    schedule.every(1).seconds.do(ensure_schedule_3)
    while 1:
        schedule.run_pending()
run()