1. 安装模块

pip install

2.配置

1. 在setting.py文件中进行配置
INSTALLED_APPS = [
...
'django_apscheduler',
...
]
2. 数据迁移,执行迁移操作会多出两个表:django_apscheduler_djangojob、django_apscheduler_djangojobexecution

2.1 django_apscheduler_djangojob:用于存储任务的表格 job_state: 是将任务具体的执行代码和参数进行序列化后存在了这里
2.2 django_apscheduler_djangojobexecution:用于存储任务执行状态的表格 status: 执行状态 duration: 执行了多长时间 exception: 是否出现了什么异常

python manage.py migrate

4. 使用:在view.py中实现代码

import time
from apscheduler.schedulers.background import BackgroundSchedulerfrom django.shortcuts import renderfrom django_apscheduler.jobstores import DjangoJobStore, register_job, register_eventsfrom blog.robin_server.paramiko_test import SSHConnection
try:
# 实例化调度器
scheduler = BackgroundScheduler()
# 调度器使用DjangoJobStore()
scheduler.add_jobstore(DjangoJobStore(), "default")
# 设置定时任务,选择方式为interval,时间间隔为60s
@register_job(scheduler, "interval", seconds=60, id="scheduler_test")
def test_job():
# 这里写你要执行的任务
obj = SSHConnection()
obj.run()
register_events(scheduler)
scheduler.start()
except Exception as e:
print(e)
# 有错误的话,就停止定时器
scheduler.shutdown()