@register_job(scheduler, ‘date‘, id=‘test‘, run_date=‘2019-07-07 22:49:00‘) 注:在亲测时,执行完任务会报错,原因时执行完任务后会去mysql中删除djangojob表中的任务。但是djangojobexecution表记录着执行结果,有外键关联着djangojob表,所以删除时显示有外键约束错误。但是任务会正常执行,执行之后也会正常删除。还有些其他的参数感兴趣的同学可以查看源代码来了解。
def add_job(self, func, trigger=None, args=None, kwargs=None, id=None, name=None,
misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined,
next_run_time=undefined, jobstore=‘default‘, executor=‘default‘,
replace_existing=False, **trigger_args):
"""
add_job(func, trigger=None, args=None, kwargs=None, id=None, name=None, misfire_grace_time=undefined, coalesce=undefined, max_instances=undefined, next_run_time=undefined, jobstore=‘default‘, executor=‘default‘, replace_existing=False, **trigger_args)
Adds the given job to the job list and wakes up the scheduler if it‘s already running.
Any option that defaults to ``undefined`` will be replaced with the corresponding default
value when the job is scheduled (which happens when the scheduler is started, or
immediately if the scheduler is already running).
The ``func`` argument can be given either as a callable object or a textual reference in
the ``package.module:some.object`` format, where the first half (separated by ``:``) is an
importable module and the second half is a reference to the callable object, relative to
the module.
The ``trigger`` argument can either be:
#. the alias name of the trigger (e.g. ``date``, ``interval`` or ``cron``), in which case
any extra keyword arguments to this method are passed on to the trigger‘s constructor
#. an instance of a trigger class
:param func: callable (or a textual reference to one) to run at the given time
:param str|apscheduler.triggers.base.BaseTrigger trigger: trigger that determines when
``func`` is called
:param list|tuple args: list of positional arguments to call func with
:param dict kwargs: dict of keyword arguments to call func with
:param str|unicode id: explicit identifier for the job (for modifying it later)
:param str|unicode name: textual description of the job
:param int misfire_grace_time: seconds after the designated runtime that the job is still
allowed to be run (or ``None`` to allow the job to run no matter how late it is)
:param bool coalesce: run once instead of many times if the scheduler determines that the
job should be run more than once in succession
:param int max_instances: maximum number of concurrently running instances allowed for this
job
:param datetime next_run_time: when to first run the job, regardless of the trigger (pass
``None`` to add the job as paused)
:param str|unicode jobstore: alias of the job store to store the job in
:param str|unicode executor: alias of the executor to run the job with
:param bool replace_existing: ``True`` to replace an existing job with the same ``id``
(but retain the number of runs from the existing one)
:rtype: Job
"""
job_kwargs = {
‘trigger‘: self._create_trigger(trigger, trigger_args),
‘executor‘: executor,
‘func‘: func,
‘args‘: tuple(args) if args is not None else (),
‘kwargs‘: dict(kwargs) if kwargs is not None else {},
‘id‘: id,
‘name‘: name,
‘misfire_grace_time‘: misfire_grace_time,
‘coalesce‘: coalesce,
‘max_instances‘: max_instances,
‘next_run_time‘: next_run_time
}
job_kwargs = dict((key, value) for key, value in six.iteritems(job_kwargs) if
value is not undefined)
job = Job(self, **job_kwargs)
# Don‘t really add jobs to job stores before the scheduler is up and running
with self._jobstores_lock:
if self.state == STATE_STOPPED:
self._pending_jobs.append((job, jobstore, replace_existing))
self._logger.info(‘Adding job tentatively -- it will be properly scheduled when ‘
‘the scheduler starts‘)
else:
self._real_add_job(job, jobstore, replace_existing)
return job
如何页面设定,定时任务时间
ef test_add_task(request):
if request.method == ‘POST‘:
content = json.loads(request.body.decode()) # 接收参数
try:
start_time = content[‘start_time‘] # 用户输入的任务开始时间, ‘10:00:00‘
start_time = start_time.split(‘:‘)
hour = int(start_time)[0]
minute = int(start_time)[1]
second = int(start_time)[2]
s = content[‘s‘] # 接收执行任务的各种参数
# 创建任务
scheduler.add_job(test, ‘cron‘, hour=hour, minute=minute, second=second, args=[s])
code = ‘200‘
message = ‘success‘
except Exception as e:
code = ‘400‘
message = e
back = {
‘code‘: code,
‘message‘: message
}
return JsonResponse(json.dumps(data, ensure_ascii=False), safe=False)
django-apscheduler框架还提供了很多操作定时任务的函数。比如:
scheduler.remove_job(job_name)scheduler.pause_job(job_name)scheduler.resume_job(job_name)scheduler.modify_job(job_name) 注:修改任务只能修改参数,如果要修改执行时间的话,就把任务删了重新创建。可以在页面上做一个这样的表格,再加上简单的前后端交互就可以让用户自行管理定时任务:
原文:https://www.cnblogs.com/SunshineKimi/p/14879465.html