当前位置: 首页>>代码示例>>Python>>正文


Python date.DateTrigger方法代码示例

本文整理汇总了Python中apscheduler.triggers.date.DateTrigger方法的典型用法代码示例。如果您正苦于以下问题:Python date.DateTrigger方法的具体用法?Python date.DateTrigger怎么用?Python date.DateTrigger使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在apscheduler.triggers.date的用法示例。


在下文中一共展示了date.DateTrigger方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: dict_to_trigger

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def dict_to_trigger(trigger_dict):
    """
    Returns a trigger version of the trigger json
    """
    if trigger_dict["type"] == "date":
        if "args" not in trigger_dict:
            raise APIError("Missing trigger args")
        if "date" not in trigger_dict["args"]:
            raise APIError("Invalid trigger args")

        try:
            trigger = DateTrigger(run_date=arrow.get(trigger_dict["args"]["date"]).datetime)
        except arrow.parser.ParserError:
            raise APIError("Invalid date format")

        return trigger
    else:
        raise APIError("Invalid trigger type") 
开发者ID:BBVA,项目名称:chaos-monkey-engine,代码行数:20,代码来源:executors_blueprint.py

示例2: auto_job

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def auto_job(self):
        after_60s = datetime.datetime.now()+datetime.timedelta(seconds=60)

        # spider 为20分钟间隔
        self.scheduler.add_job(
            self.send_spider_news_async,
            trigger=IntervalTrigger(minutes=20, start_date=after_60s),
            misfire_grace_time=60,
            coalesce=True,
            max_instances=1,
        )

        # 每个 rss 启动第一个任务
        subscribes = [s for s in self.rss.keys() if self.setting.get(s, True)]
        for source in subscribes:
            self.scheduler.add_job(
                self.send_rss_news_async,
                args=(source,),
                id=source,
                trigger=DateTrigger(after_60s),
                misfire_grace_time=60,
                coalesce=True,
                max_instances=1,
            ) 
开发者ID:yuudi,项目名称:yobot,代码行数:26,代码来源:push_news.py

示例3: send_rss_news_async

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def send_rss_news_async(self, source):
        # 执行时间改为5分钟后
        self.scheduler.add_job(
            self.send_rss_news_async,
            args=(source,),
            id=source,
            jobstore='default',
            misfire_grace_time=60,
            coalesce=True,
            max_instances=1,
            trigger=DateTrigger(
                datetime.datetime.now()+datetime.timedelta(minutes=5)
            ),
        )
        res = await self.from_rss_async(source)
        await self.send_news_msg_async([res]) 
开发者ID:yuudi,项目名称:yobot,代码行数:18,代码来源:push_news.py

示例4: trigger_to_dict

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def trigger_to_dict(trigger):
    """
    Returns a dict version of the trigger
    """
    if isinstance(trigger, DateTrigger):
        trigger_dict = {}
        trigger_dict["type"] = "date"
        trigger_dict["args"] = {"date": arrow.get(trigger.run_date).isoformat()}
        return trigger_dict 
开发者ID:BBVA,项目名称:chaos-monkey-engine,代码行数:11,代码来源:executors_blueprint.py

示例5: step_impl

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def step_impl(context):
    """run the executor in context.executors_to_run"""
    for executor in context.executors_to_run:
        now = datetime.now() + timedelta(seconds=2)
        trigger = DateTrigger(run_date=now)
        context.manager.update_executor_trigger(executor.id, trigger)

        # give time to execute the jobs
        wait_for_job_executed(context, executor.id)

        context.last_executor_id = executor.id 
开发者ID:BBVA,项目名称:chaos-monkey-engine,代码行数:13,代码来源:scheduler.py

示例6: test_date_trigger_to_dict

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def test_date_trigger_to_dict():
    my_dt = arrow.get("2016-06-21T15:30:12").datetime
    trigger = DateTrigger(run_date=my_dt)
    trigger_dict = {"type": "date", "args": {"date": "2016-06-21T15:30:12+00:00"}}
    assert trigger_dict == trigger_to_dict(trigger) 
开发者ID:BBVA,项目名称:chaos-monkey-engine,代码行数:7,代码来源:executors_blueprint_test.py

示例7: _add_job_to_scheduler

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def _add_job_to_scheduler(self, trigger):
        trigger_type_ref = trigger['type']
        trigger_type = TIMER_TRIGGER_TYPES[trigger_type_ref]
        try:
            util_schema.validate(instance=trigger['parameters'],
                                 schema=trigger_type['parameters_schema'],
                                 cls=util_schema.CustomValidator,
                                 use_default=True,
                                 allow_default_none=True)
        except jsonschema.ValidationError as e:
            LOG.error('Exception scheduling timer: %s, %s',
                      trigger['parameters'], e, exc_info=True)
            raise  # Or should we just return?

        time_spec = trigger['parameters']
        time_zone = aps_utils.astimezone(trigger['parameters'].get('timezone'))

        time_type = None

        if trigger_type['name'] == 'st2.IntervalTimer':
            unit = time_spec.get('unit', None)
            value = time_spec.get('delta', None)
            time_type = IntervalTrigger(**{unit: value, 'timezone': time_zone})
        elif trigger_type['name'] == 'st2.DateTimer':
            # Raises an exception if date string isn't a valid one.
            dat = date_parser.parse(time_spec.get('date', None))
            time_type = DateTrigger(dat, timezone=time_zone)
        elif trigger_type['name'] == 'st2.CronTimer':
            cron = time_spec.copy()
            cron['timezone'] = time_zone

            time_type = CronTrigger(**cron)

        utc_now = date_utils.get_datetime_utc_now()
        if hasattr(time_type, 'run_date') and utc_now > time_type.run_date:
            LOG.warning('Not scheduling expired timer: %s : %s',
                        trigger['parameters'], time_type.run_date)
        else:
            self._add_job(trigger, time_type)
        return time_type 
开发者ID:StackStorm,项目名称:st2,代码行数:42,代码来源:base.py

示例8: _normalize_coerce_date

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def _normalize_coerce_date(self, value: str) -> Tuple[Type, Tuple[str]]:
        return DateTrigger, (value,) 
开发者ID:funkyfuture,项目名称:deck-chores,代码行数:4,代码来源:parsers.py

示例9: add_job

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def add_job(self, job, name=None, max_instances=1, coalesce=True, args=None):
        self.aps_scheduler.add_job(
            job, DateTrigger(run_date=datetime.now()), name=name, id=name, max_instances=max_instances,
            coalesce=coalesce, args=args) 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:6,代码来源:scheduler.py

示例10: build_trigger

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def build_trigger(self, type, value):
        """
        build a trigger for a schuduled job
        :param type: cron, interval, delta, date
        :param value: value to convert for a scheduled job
        :return: appropriate trigger
        """

        trigger = None
        if type == "cron":

            split_cron = value.split(" ")
            trigger = CronTrigger(minute=split_cron[0],
                                  hour=split_cron[1],
                                  day=split_cron[2],
                                  month=split_cron[3],
                                  day_of_week=split_cron[4])

        elif type == "interval":
            seconds = self.get_interval(value)
            trigger = IntervalTrigger(seconds=seconds)

        elif type == "date":
            trigger = DateTrigger(run_date=value, timezone=self.timezone)

        elif type == "delta":
            dt = self.get_interval(value, date=True)
            trigger = DateTrigger(run_date=dt, timezone=self.timezone)

        else:
            raise ValueError("Unrecognized type %s", type)

        return trigger 
开发者ID:ibmresilient,项目名称:resilient-community-apps,代码行数:35,代码来源:scheduler_helper.py

示例11: schedule_callback

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def schedule_callback(id, func=None, remove_job=False, args=None, **kwargs):
    if ACTIVITY_SCHED.get_job(id):
        if remove_job:
            ACTIVITY_SCHED.remove_job(id)
        else:
            ACTIVITY_SCHED.reschedule_job(
                id, args=args, trigger=DateTrigger(
                    run_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(**kwargs),
                    timezone=pytz.UTC))
    elif not remove_job:
        ACTIVITY_SCHED.add_job(
            func, args=args, id=id, trigger=DateTrigger(
                run_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(**kwargs),
                timezone=pytz.UTC)) 
开发者ID:Tautulli,项目名称:Tautulli,代码行数:16,代码来源:activity_handler.py

示例12: jobs

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def jobs(self):
        time = self.setting.get("calender_time", "08:00")
        hour, minute = time.split(":")
        trigger = CronTrigger(hour=hour, minute=minute)
        job = (trigger, self.send_daily_async)
        init_trigger = DateTrigger(
            datetime.datetime.now() +
            datetime.timedelta(seconds=5)
        )  # 启动5秒后初始化
        init_job = (init_trigger, self.load_timeline_async)
        return (job, init_job) 
开发者ID:yuudi,项目名称:yobot,代码行数:13,代码来源:calender.py

示例13: put_executor

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def put_executor(executor_id):
    """
    Update a executor to change its date. To provide a new date use the format
    in the example bellow.
    The format is used to create a
    `DateTrigger <https://github.com/agronholm/apscheduler/blob/master/apscheduler/triggers/date.py>`_
    from the apscheduler.

    TODO: create more `Triggers <https://github.com/agronholm/apscheduler/blob/master/apscheduler/triggers>`_

    Example request::

        PUT /api/1/executors/3b373155577b4d1bbc62216ffea013a4
        Body:
            {
              "type" : "date",
              "args" : {
                "date": "2017-10-23T19:19"
              }
            }

    Example response::

        {
          "id": "3b373155577b4d1bbc62216ffea013a4",
          "plan_id": "3ec72048cab04b76bdf2cfd4bc81cd1e",
          "next_run_time": "2017-10-23T19:19:1508786354",
          "executed": false,
          "_links": {
            "self": {
              "href": "/api/1/executors/3b373155577b4d1bbc62216ffea013a4"
            },
            "update":{
              "href":"/api/1/executors/3b373155577b4d1bbc62216ffea013a4"
            },
            "delete":{
              "href":"/api/1/executors/3b373155577b4d1bbc62216ffea013a4"
            }
          }
        }

    :return: :meth:`chaosmonkey.api.hal.document`
    """
    assert validate_payload(request, executor_trigger_schema)
    body = request.get_json()

    trigger = dict_to_trigger(body)

    try:
        executor = manager.update_executor_trigger(executor_id, trigger)
    except JobLookupError:
        return json.jsonify({"msg": "executor not found " + executor_id}), 404
    else:
        return Document(data=executor.to_dict()) 
开发者ID:BBVA,项目名称:chaos-monkey-engine,代码行数:56,代码来源:executors_blueprint.py

示例14: job_to_json

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def job_to_json(job):
        """
        rebuild type of scheduled job
        :param job:
        :return: json string with argument similar to use when job originally scheduled
        """
        result = {
            "id": job.id,
            "args": job.args,
            "next_run_time": ResilientScheduler.get_str_date(job.next_run_time)
        }

        if isinstance(job.trigger, IntervalTrigger):
            result['type'] = 'interval'
            value = None

            if int(job.trigger.interval_length % SECONDS_IN_WEEK) == 0:
                value = str(int(job.trigger.interval_length / SECONDS_IN_WEEK)) + "w"
            elif int(job.trigger.interval_length % SECONDS_IN_DAY) == 0:
                value = str(int(job.trigger.interval_length / SECONDS_IN_DAY)) + "d"
            elif int(job.trigger.interval_length % SECONDS_IN_HOUR) == 0:
                value = str(int(job.trigger.interval_length / SECONDS_IN_HOUR)) + "h"
            elif int(job.trigger.interval_length % SECONDS_IN_MINUTE) == 0:
                value = str(int(job.trigger.interval_length / SECONDS_IN_MINUTE)) + "m"
            else:
                value = str(job.trigger.interval_length) + "s"

            result['value'] = value

        elif isinstance(job.trigger, CronTrigger):
            result['type'] = 'cron'
            job_state = job.trigger.__getstate__()
            cron = ['*', '*', '*', '*', '*']
            for field in job_state['fields']:
                if field.name == "minute":
                    cron[0] = str(field)
                elif field.name == "hour":
                    cron[1] = str(field)
                elif field.name == "day":
                    cron[2] = str(field)
                elif field.name == "month":
                    cron[3] = str(field)
                elif field.name == "day_of_week":
                    cron[4] = str(field)
                #elif field.name == "year":
                #    cron[5] = str(field)

            result['value'] = ' '.join(cron)

        elif isinstance(job.trigger, DateTrigger):
            result['type'] = 'date'
            job_state = job.trigger.__getstate__()
            result['value'] = ResilientScheduler.get_str_date(job_state['run_date'])

        else:
            result['type'] = 'unknown'
            result['value'] = None

        return result 
开发者ID:ibmresilient,项目名称:resilient-community-apps,代码行数:61,代码来源:scheduler_helper.py

示例15: from_rss_async

# 需要导入模块: from apscheduler.triggers import date [as 别名]
# 或者: from apscheduler.triggers.date import DateTrigger [as 别名]
def from_rss_async(self, source) -> str:
        rss_source = self.rss[source]
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
              + "检查RSS源:{}".format(rss_source["name"]))
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(rss_source["source"], headers=rss_source.get("headers")) as response:
                    code = response.status
                    if code != 200:
                        print("rss源错误:{},返回值:{}".format(
                            rss_source["name"], code))
                        return None
                    res = await response.text()
        except aiohttp.client_exceptions.ClientConnectionError:
            print("rss源连接错误:"+rss_source["name"])
            return None
        except Exception as e:
            print("未知错误{} {}".format(type(e).__name__, e))
            return None
        feed = feedparser.parse(res)
        if feed["bozo"]:
            print("rss源解析错误:"+rss_source["name"])
            return None
        if self.news_interval_auto:
            updated = feed.feed.updated
            if updated is not None:
                # 获取rss上次刷新时间
                lastBuildDate = parsedate_tz(updated)
                nt = datetime.datetime.fromtimestamp(
                    time.mktime(lastBuildDate[:-1])
                    - lastBuildDate[-1]
                    + 28800)
                nt += datetime.timedelta(minutes=25)
                after10min = datetime.datetime.now()+datetime.timedelta(minutes=10)
                if nt > after10min:
                    # 执行时间改为上次刷新后25分钟
                    self.scheduler.reschedule_job(
                        job_id=source,
                        jobstore='default',
                        trigger=DateTrigger(nt),
                    )
        last_id = rss_source.get("last_id")
        rss_source["last_id"] = feed["entries"][0]["id"]
        if last_id is None:
            print("rss初始化:"+rss_source["name"])
            return None
        news_list = list()
        for item in feed["entries"]:
            if item["id"] == last_id:
                break
            news_list.append(rss_source["pattern"].format_map(item))
        if news_list:
            return (rss_source["name"]+"更新:\n=======\n"
                    + "\n-------\n".join(news_list))
        else:
            return None 
开发者ID:yuudi,项目名称:yobot,代码行数:58,代码来源:push_news.py


注:本文中的apscheduler.triggers.date.DateTrigger方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。