扩展 StoryBoard:Cron 插件

概述

StoryBoard 需要偶尔执行周期性任务,以支持清理和维护等功能。它通过直接管理自己的 crontab 条目来实现这一点,并且提供了扩展钩子供您添加自己的功能。Crontab 条目每 5 分钟检查一次,会添加新的条目并删除旧的/孤立的条目。请注意,此监控仅在 storyboard api 运行时有效。一旦 API 关闭,所有 cron 插件也会关闭。

当您的插件执行时,它通过 storyboard-cron 启动配置和 storyboard 来完成。它不维护运行之间的状态,并且在您的代码完成后立即终止。

我们不建议您使用此扩展机制来创建长期运行的进程。在执行您的插件的 run() 方法时,您将获得上次执行的时间以及当前时间戳。请将您的插件的执行范围限制在发生在该时间范围内的事件,并在之后退出。

Cron 插件快速入门

步骤 1:使用 setuptools 创建一个新的 Python 项目

这留作练习给读者。不要忘记将 storyboard 作为依赖项包含进去。

步骤 2:实现您的插件

在您的插件的 setup.cfg 中添加一个注册的入口点。名称应合理且唯一

[entry_points]
storyboard.plugin.cron =
     my-plugin-cron = my.namespace.plugin:CronWorker

然后,通过扩展 CronPluginBase 来实现您的插件。您可以注册自己的配置组,请参阅 oslo.config 以获取更多详细信息。

from storyboard.plugin.cron.base import CronPluginBase

class MyCronPlugin(CronPluginBase):

    def enabled(self):
        '''This method should return whether the plugin is enabled and
        configured. It has access to self.config, which is a reference to
        storyboard's global configuration object.
        '''
        return True

    def interval(self):
        '''This method should return the crontab interval for this
        plugin's execution schedule. It is used verbatim.
        '''
        return "? * * * *"

    def run(self, start_time, end_time):
        '''Execute your plugin. The provided parameters are the start and
        end times of the time window for which this particular execution
        is responsible.

        This particular implementation simply deletes oauth tokens that
        are older than one week.
        '''

        lastweek = datetime.utcnow() - timedelta(weeks=1)

        query = api_base.model_query(AccessToken)
        query = query.filter(AccessToken.expires_at < lastweek)
        query.delete()

步骤 3:安装您的插件

最后,安装您的插件,这可能需要您切换到 storyboard 的虚拟环境。Pip 应该会自动注册您的插件

pip install my-storyboard-plugin