我必须允许管理员从Django的admin视图中设置cron时间。 就像我有一个配置模型一样,管理员可以在其中将时间记录为
因此,在每条记录上,我都必须运行cron。 但是cron时间在setting.py
set apps=
set apps_defined=
for /d %%s in (".\manifests\*.xml") do (
for /f "tokens=*" %%g in ('xml sel -t -v "\apps\app" %cd%\manifests\%%s') do (
echo Found app - %%g [inside %%s]
if not "apps_defined[%%g]"=="true" (
if not "!apps!"=="" set apps=!apps!,
set apps=!apps!%%g
)
set apps_defined[%%g]=true
)
)
https://pypi.org/project/django-crontab/
如何使此设置可用于管理员。
答案 0 :(得分:1)
我看不到任何好的方法,因为vanilla django_crontab仅允许从设置填充crontab。您最好找到其他可以满足您需求的软件包。但是,如果您别无选择,我认为以下方法会起作用:
from django_crontab.app_settings import Settings
from django_crontab.crontab import Crontab
from django.conf import settings
# function need to return crontab
# in the same format as settings.py
def populate_from_db():
# some db magic
return [('*/5 * * * *', 'myapp.cron.my_scheduled_job')]
class DBCronSettings(Settings):
def __init__(self, settings):
super().__init__(settings)
self.CRONJOBS = populate_from_db() #
class DBCrontab(Crontab):
def __init__(self, **options):
super().__init__(**options)
self.settings = DBCronSettings(settings)
您需要子类化Crontab和设置。使DBCronSettings从数据库中读取您的cron作业,然后在自定义DBCrontab中使用此设置。
然后创建您自己的crontab命令。处理方法与基本命令中的方法完全相同,但是使用的是DBCrontab类,而不是原始类。
from django_crontab.management.commands.crontab import Command as CrontabCommand
from my_crontab import DBCrontab as Crontab
class Command(CrontabCommand):
def handle(self, *args, **options):
"""
Dispatches by given subcommand
"""
if options['subcommand'] == 'add': # add command
with Crontab(**options) as crontab: # initialize a Crontab class with any specified options
crontab.remove_jobs() # remove all jobs specified in settings from the crontab
crontab.add_jobs() # and add them back
elif options['subcommand'] == 'show': # show command
# initialize a readonly Crontab class with any specified options
with Crontab(readonly=True, **options) as crontab:
crontab.show_jobs() # list all currently active jobs from crontab
elif options['subcommand'] == 'remove': # remove command
with Crontab(**options) as crontab: # initialize a Crontab class with any specified options
crontab.remove_jobs() # remove all jobs specified in settings from the crontab
elif options['subcommand'] == 'run': # run command
Crontab().run_job(options['jobhash']) # run the job with the specified hash
else:
# output the help string if the user entered something not specified above
print(self.help)
如果您计划将命令命名为“ crontab”,也不要忘记从INSTALLED_APPS中删除django_crontab。