Django 定时任务

本文介绍怎么在一个django的项目里增加定时任务。

使用的框架为APScheduler, 安装APScheduler:

1

pip install apscheduler==2.1.2

 安装完成后,打开django web 项目的urls.py 增加以下内容:

1

2

3

4

5

6

7

8

9

10

from apscheduler.scheduler import  Scheduler

from siteathome import tests

 

sched = Scheduler()

 

@sched.interval_schedule(seconds=60)

def my_task():

    tests.testFuncton()

 

sched.start()

其中, siteathome.tests 里面的testFunction()是需要被定时执行的任务,这里定义每60秒执行一次。

def testFuncton():
    print("Hello Scheduler")

启动django 项目, 观察控制台,每60秒会有一个Hello Scheduler 输出:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Performing system checks...

 

System check identified no issues (0 silenced).

 

You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.

Run 'python manage.py migrate' to apply them.

November 15, 2017 - 21:42:16

Django version 1.11, using settings 'djangoathome.settings'

Starting development server at http://127.0.0.1:8000/

Quit the server with CTRL-BREAK.

Hello Scheduler

Hello Scheduler

Hello Scheduler

Hello Scheduler

Hello Scheduler

Hello Scheduler

Hello Scheduler

Hello Scheduler

你可能感兴趣的:(APScheduler)