Skip to content

Instantly share code, notes, and snippets.

@zengxs
Created Nov 10, 2021
Embed
What would you like to do?
import logging
import pytz
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.schedulers.background import BackgroundScheduler
from django.utils.deprecation import MiddlewareMixin
from django.utils.timezone import get_current_timezone_name
logger = logging.getLogger(__name__)
def print_hello():
print("hello world")
class APSchedulerMiddleware(MiddlewareMixin):
def __init__(self, get_response):
super().__init__(get_response)
self.scheduler = BackgroundScheduler(
jobstores={'default': RedisJobStore(host='localhost', db=0)},
executors={'default': ThreadPoolExecutor(max_workers=20)},
timezone=pytz.timezone(get_current_timezone_name()),
)
self.scheduler.start()
# Django 启动时创建一个定时任务
self.scheduler.add_job(print_hello, 'interval', seconds=15, id='print_hello')
def process_request(self, request):
setattr(request, 'scheduler', self.scheduler)
@watsonhaw5566
Copy link

watsonhaw5566 commented Feb 18, 2022

nice 学习

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment