/middlewares.py Secret
Created
November 10, 2021 12:30
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice 学习