博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python Apscheduler源代码解析(一) 任务调度流程
阅读量:6907 次
发布时间:2019-06-27

本文共 1789 字,大约阅读时间需要 5 分钟。

最近公司有项目需要使用到定时任务,其定时逻辑类似于linux的Cron,就使用了Apscheduler这个类库。基于公司的业务,需要修改Apshceduler,故而研究了一下Apscheduler的代码。

Apscheduler的调度逻辑非常简单,越简单的东西往往也越有效。

调度器会开辟一个线程,这个线程会循环的从job_store中找到任务,计算任务的执行时间,并与当前时间做比较。如果任务的执行事件<=当前时间,就将任务的firetime放到一个列表中(runtimes)

def _get_run_times(self, now):        run_times = []        next_run_time = self.next_run_time        while next_run_time and next_run_time <= now:            run_times.append(next_run_time)            next_run_time = self.trigger.get_next_fire_time(next_run_time, now)        return run_times

如果runtimes不为空,就将其放入Executor中,下面代码中的executor不是Python的线程池类,是Apscheduler的一个类,当然了,最终的结果是将任务放到线程池当中

if run_times:                    try:                        executor.submit_job(job, run_times)

在BaseExecutor类中,有一个abstract method,负责将任务放到线程池当中,在其子类BasePoolExecutor中,继承了这个方法

def _do_submit_job(self, job, run_times):        def callback(f):            exc, tb = (f.exception_info() if hasattr(f, 'exception_info') else                       (f.exception(), getattr(f.exception(), '__traceback__', None)))            if exc:                self._run_job_error(job.id, exc, tb)            else:                self._run_job_success(job.id, f.result())        f = self._pool.submit(run_job, job, job._jobstore_alias, run_times, self._logger.name)        f.add_done_callback(callback)

代码中的self._pool可以是线程池,也可以是进程池,在concurrent.futures包中,已经是python3的标准类库了。

关于调度器的事件循环,如果让他一直循环不断的从job_store中取任务,然后判断,这样会十分浪费资源。Apscheduler在一次循环结束之前会计算任务下次执行事件与当前时间之差,然后让调度线程挂起直到那个时间到来。

def _main_loop(self):        wait_seconds = TIMEOUT_MAX        while self.state != STATE_STOPPED:            self._event.wait(wait_seconds)            self._event.clear()            wait_seconds = self._process_jobs()

self._process_jobs()的返回值就是上面说的那个时间,self._event.wait(wait_seconds)就是让当前线程等待这么长的一段时间

转载地址:http://mhfcl.baihongyu.com/

你可能感兴趣的文章
listview设置item间距和颜色渐变
查看>>
CentOS — 安装LevelDB & PHP LevelDB扩展
查看>>
C++深拷贝与浅拷贝
查看>>
构造方法
查看>>
python mysql 安装包下载
查看>>
java基本语法注意问题
查看>>
poj1317
查看>>
CListCtrl获取当前选中行索引号
查看>>
帮助-阅读随笔
查看>>
Installing C++ Boost on Microsoft Windows for Visual Studio .NET 2003/2005/Orcas
查看>>
实例化需求—流程
查看>>
MonoDevelop添加NuGet支持
查看>>
响应式的前端框架 - Groundwork
查看>>
json格式化和查看工具
查看>>
uml基础
查看>>
[Linux] 批量转换整个目录下的文件编码为UTF-8;
查看>>
【转】>Unity3d动态数据管理(Export AssetBundles)
查看>>
C++new delete 动态申请二维数组
查看>>
Android Service:Creating a Started Service
查看>>
HDU-4512 吉哥系列故事——完美队形I 最长公共上升子序列
查看>>