Python schedule.every() Examples
The following are 30
code examples of schedule.every().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
schedule
, or try the search function
.
Example #1
Source File: scheduler.py From haipproxy with MIT License | 7 votes |
def schedule_with_delay(self): for task in self.tasks: interval = task.get('interval') schedule.every(interval).minutes.do(self.schedule_task_with_lock, task) while True: schedule.run_pending() time.sleep(1)
Example #2
Source File: xuexi.py From autoxuexi with GNU General Public License v3.0 | 7 votes |
def go_click(self): self.save_settings() schedule.clear() if config['schedule']['schedule_time']: schedule.every().day.at(config['schedule']['schedule_time']).do(self.start_click, sched_task=True) else: schedule.every().day.at("08:00").do(self.start_click) try: self.task_monitor.isAlive() except AttributeError: self.task_monitor = threading.Thread(target=self.run_monitor) else: if not self.task_monitor.isAlive(): self.task_monitor = threading.Thread(target=self.run_monitor) finally: if not self.task_monitor.isAlive(): self.task_monitor.setDaemon(True) self.task_monitor.start() app.log('当前账号: %s' % config['dingtalk']['username']) app.log('等待下次学习时间: %s' % schedule.next_run())
Example #3
Source File: daily_report.py From selene-backend with GNU Affero General Public License v3.0 | 7 votes |
def _run(self): if self.args.run_mode == 'job': schedule.every().day.at('00:00').do(self._build_report) while True: schedule.run_pending() time.sleep(1) else: self._build_report(self.args.date)
Example #4
Source File: smart_module.py From hapi with GNU General Public License v3.0 | 7 votes |
def prepare_jobs(self, jobs): suffixed_names = { 'week': 'weekly', 'day': 'daily', 'hour': 'hourly', 'minute': 'minutes', 'second': 'seconds', } for job in jobs: if not job.enabled: continue interval_name = job.time_unit.lower() if job.interval > 0: # There can't be a job less than 0 (0 minutes? 0 seconds?) plural_interval_name = interval_name + 's' d = getattr(schedule.every(job.interval), plural_interval_name) d.do(self.run_job, job) Log.info(" Loading %s job: %s.", suffixed_names[interval_name], job.name) elif interval_name == 'day': schedule.every().day.at(job.at_time).do(self.run_job, job) Log.info(" Loading time-based job: " + job.name) else: d = getattr(schedule.every(), interval_name) d.do(self.run_job, job) Log.info(" Loading %s job: %s", interval_name, job.name)
Example #5
Source File: sched.py From ab-2018 with GNU General Public License v3.0 | 6 votes |
def user_callback(ch, method, properties, body): user_json = body.decode() user_dict = json.loads(user_json) r.set("User:{}".format(user_dict["email"]), user_json) schedule.every(periods[user_dict['period']]).days.at("10:00").do( sub_ch.basic_publish, exchange='work', routing_key=SCHEDULE_NOTIFIER_QUEUE, body=user_dict["email"]) for s in user_dict['subscriptions'].keys(): for g in user_dict['subscriptions'][s]: sub_ch.basic_publish(exchange='work', routing_key=funcs[s], body=g) schedule.every(periods[user_dict['period']]).days.at("10:00").do( sub_ch.basic_publish, exchange='work', routing_key=funcs[s], body=g )
Example #6
Source File: test_async_tools.py From lightbus with Apache License 2.0 | 6 votes |
def test_call_on_schedule_async(run_for): import schedule await_count = 0 async def cb(): nonlocal await_count await_count += 1 await run_for( coroutine=call_on_schedule( callback=cb, schedule=schedule.every(0.1).seconds, also_run_immediately=False ), seconds=0.25, ) assert await_count == 2
Example #7
Source File: run.py From baleen with MIT License | 6 votes |
def handle(self, args): logger = IngestLogger() logger.info( "Starting Baleen v{} ingestion service every hour.".format(baleen.get_version()) ) schedule.every().hour.do(partial(self.ingest, args)) while True: try: schedule.run_pending() time.sleep(1) except (KeyboardInterrupt, SystemExit): logger.info("Graceful shutdown of Baleen ingestion service.") return "" except Exception as e: logger.critical(str(e)) return str(e)
Example #8
Source File: jobs.py From sensu_drive with MIT License | 6 votes |
def handle(self, *args, **kwargs): logger.info("%s - starting jobs schedule" % (__name__)) try: ''' schedule.every().hour.do(job_update_entities) schedule.every().hour.do(job_update_clients) schedule.every().hour.do(job_update_checks) schedule.every().hour.do(job_update_trends) #schedule.every(10).minutes.do(job_update_events) ''' schedule.every(settings.CACHE_ENTITY_TTL).seconds.do(job_update_entities) schedule.every(settings.CACHE_CLIENT_TTL).seconds.do(job_update_clients) schedule.every(settings.CACHE_TRENDS_TTL).seconds.do(job_update_trends) while True: schedule.run_pending() sleep(1) except KeyboardInterrupt: logger.info("%s - user signal exit!" % (__name__)) exit(0)
Example #9
Source File: timeline.py From kibitzr with MIT License | 6 votes |
def _clean_single_schedule(cls, check, schedule_dict): if not isinstance(schedule_dict, dict): raise ConfigurationError( 'Check {0} has invalid schedule configuration: {1}' .format(check['name'], schedule_dict), ) try: every = schedule_dict['every'] except KeyError: raise ConfigurationError( "Check {0} has invalid schedule format: {1}" .format(check['name'], schedule_dict) ) if isinstance(every, six.string_types): # "every: day" shortcut unit, every = every, 1 else: unit = schedule_dict.get('unit') unit = cls._clean_unit(check, unit) at = cls._clean_at(check, schedule_dict.get('at')) rule = TimelineRule(every, unit, at) logger.debug('Parsed schedule "%r" to %r', schedule_dict, rule) return rule
Example #10
Source File: controller.py From GaragePi with MIT License | 6 votes |
def __init__(self, port="5550"): self.__bind_addr = "tcp://*:%s" % port app.logger.info("Bind address: " + self.__bind_addr) self.__relay_lock = threading.Lock() self.__db = GarageDb(app.instance_path, app.resource_path) # Get initial reed state and subscribe to events GPIO.setup(app.config['REED_PIN'], GPIO.IN) GPIO.add_event_detect(app.config['REED_PIN'], GPIO.BOTH, callback=self.door_opened_or_closed) self.__door_state = None # 1 for open, 0 for closed, None for uninitialized self.door_opened_or_closed(app.config['REED_PIN']) # force update # Set up warning timer if there's a setting if app.config['DOOR_OPEN_WARNING_TIME']: app.logger.info('Starting schedule to check door at {0}...'.format(app.config['DOOR_OPEN_WARNING_TIME'])) schedule.every().day.at(app.config['DOOR_OPEN_WARNING_TIME']).do(self.check_door_open_for_warning) t = Thread(target=self.run_schedule) t.start() else: app.logger.info('No schedule to run.')
Example #11
Source File: test_bus_client_unit.py From lightbus with Apache License 2.0 | 6 votes |
def test_schedule(dummy_bus: lightbus.path.BusPath): import schedule calls = 0 # TODO: This kind of 'throw exception to stop bus' hackery in the tests can be cleaned up @dummy_bus.client.schedule(schedule.every(0.001).seconds) async def test_coroutine(): nonlocal calls while True: calls += 1 if calls == 5: raise Exception("Intentional exception: stopping lightbus dummy bus from running") await asyncio.sleep(0.001) dummy_bus.client.run_forever() assert dummy_bus.client.exit_code assert calls == 5
Example #12
Source File: scheduler.py From PyTrendFollow with MIT License | 6 votes |
def set_schedule(time): schedule.every().monday.at(time).do(sync_trades) schedule.every().tuesday.at(time).do(sync_trades) schedule.every().wednesday.at(time).do(sync_trades) schedule.every().thursday.at(time).do(sync_trades) schedule.every().friday.at(time).do(sync_trades)
Example #13
Source File: MalShare.py From MalPipe with GNU General Public License v3.0 | 6 votes |
def __init__(self): md = MalwareFeedDescription( module_name="MalShare", interval = schedule.every().day.at("04:00"), description="Feed from MalShare of Daily files", authors=["Silas Cutler"], version="0.2" ) MalwareFeed.__init__(self, md) self.parse_settings() self.url_daily_list = "https://malshare.com/daily/malshare.current.sha256.txt" self.url_download = "https://malshare.com/api.php?api_key=%s&action=getfile&hash=%s" self.url_sources = "https://malshare.com/api.php?api_key=%s&action=getsources" # Settings
Example #14
Source File: test_bus_client_unit.py From lightbus with Apache License 2.0 | 6 votes |
def test_every(dummy_bus: lightbus.path.BusPath, event_loop): calls = 0 @dummy_bus.client.every(seconds=0.001) async def test_coroutine(): nonlocal calls while True: calls += 1 if calls == 5: raise Exception("Intentional exception: stopping lightbus dummy bus from running") await asyncio.sleep(0.001) # SystemExit raised because test_coroutine throws an exception dummy_bus.client.run_forever() assert dummy_bus.client.exit_code assert calls == 5
Example #15
Source File: test_async_tools.py From lightbus with Apache License 2.0 | 5 votes |
def test_call_on_schedule(run_for, call_counter): await run_for( coroutine=call_on_schedule( callback=call_counter, schedule=schedule.every(0.1).seconds, also_run_immediately=False ), seconds=0.25, ) assert call_counter.call_count == 2
Example #16
Source File: scheduler.py From ab-2018 with GNU General Public License v3.0 | 5 votes |
def schedule_the_job(self, period, subscriber): job_without_interval = schedule.every() if period == 'daily': job_with_an_interval = job_without_interval.day() else: job_with_an_interval = job_without_interval.week() return job_with_an_interval.do(self.notify_crawler, subscriber=subscriber)
Example #17
Source File: __init__.py From Chaos with MIT License | 5 votes |
def schedule_jobs(api, api_twitter): schedule.every(settings.PULL_REQUEST_POLLING_INTERVAL_SECONDS).seconds.do( lambda: poll_pull_requests(api, api_twitter)) schedule.every(settings.ISSUE_COMMENT_POLLING_INTERVAL_SECONDS).seconds.do( lambda: poll_read_issue_comments(api)) schedule.every(settings.ISSUE_CLOSE_STALE_INTERVAL_SECONDS).seconds.do( lambda: poll_issue_close_stale(api)) # Call manually the first time, so that we are guaranteed this will run # at least once in the interval... poll_issue_close_stale(api)
Example #18
Source File: convert.py From fogernetes with BSD 3-Clause "New" or "Revised" License | 5 votes |
def schedule_main(): print "Convert directory: %s" % config.UPLOADED_FILES_DEST convert() schedule.every(5).minutes.do(convert) while True: # print "." schedule.run_pending() time.sleep(1)
Example #19
Source File: api.py From friartuck with MIT License | 5 votes |
def _set_trigger_timer(callback_function, minute_interval=None, direct_time=None): log.debug("setting trigger direct_time=%s, minute_interval= %s " % (direct_time, minute_interval)) if not minute_interval and not direct_time: log.error("Bad trigger timer request... one of the following is required (minute_interval, direct_time)") return if direct_time: dt = direct_time else: dt = datetime.now() + timedelta(minutes=minute_interval) # update every minute dt = dt.replace(second=0, microsecond=0) str_time = dt.strftime("%H:%M") schedule.every().day.at(str_time).do(callback_function)
Example #20
Source File: Scheduler.py From hogar with MIT License | 5 votes |
def scheduler_init (parent): ''' Schedule Init Start the main loop for the internal scheduler that ticks every second. -- @param parent:int The PID of the parent. @return void ''' # Define the jobs to run at which intervals schedule.every().minute.do(Reminder.run_remind_once) schedule.every().minute.do(Reminder.run_remind_recurring) # Start the main thread, polling the schedules # every second while True: # Check if the current parent pid matches the original # parent that started us. If not, we should end. if os.getppid() != parent: logger.error( 'Killing scheduler as it has become detached from parent PID.') sys.exit(1) # Run the schedule schedule.run_pending() time.sleep(1) return
Example #21
Source File: poll_pods.py From social-relay with GNU Affero General Public License v3.0 | 5 votes |
def schedule_job(): schedule.every().hour.do(poll_pods)
Example #22
Source File: test_async_tools.py From lightbus with Apache License 2.0 | 5 votes |
def test_call_on_schedule_run_immediate(run_for, call_counter): await run_for( coroutine=call_on_schedule( callback=call_counter, schedule=schedule.every(0.1).seconds, also_run_immediately=True ), seconds=0.25, ) assert call_counter.call_count == 3
Example #23
Source File: bus_client.py From lightbus with Apache License 2.0 | 5 votes |
def __init__( self, config: "Config", schema: "Schema", plugin_registry: "PluginRegistry", hook_registry: "HookRegistry", event_client: "EventClient", rpc_result_client: "RpcResultClient", api_registry: "ApiRegistry", transport_registry: "TransportRegistry", error_queue: ErrorQueueType, features: Sequence[Union[Feature, str]] = ALL_FEATURES, ): self.config = config self.schema = schema self.plugin_registry = plugin_registry self.hook_registry = hook_registry self.event_client = event_client self.rpc_result_client = rpc_result_client self.api_registry = api_registry # The transport registry isn't actually used by the bus client, but it is # useful to have it available as a property on the client. self.transport_registry = transport_registry self.error_queue = error_queue # Coroutines added via schedule/every/add_background_task which should be started up # once the worker starts self._background_coroutines = [] # Tasks produced from the values in self._background_coroutines. Will be closed on bus shutdown self._background_tasks = [] self.features: List[Union[Feature, str]] = [] self.set_features(ALL_FEATURES) self.exit_code = 0 self._closed = False self._worker_tasks = set() self._lazy_load_complete = False # Used to detect if the event monitor is running self._error_monitor_lock = asyncio.Lock()
Example #24
Source File: bus_client.py From lightbus with Apache License 2.0 | 5 votes |
def schedule(self, schedule: "Job", also_run_immediately=False): """Call a coroutine on the specified schedule Schedule a task using the `schedule` library: import lightbus import schedule bus = lightbus.create() # Run the task every 1-3 seconds, varying randomly @bus.client.schedule(schedule.every(1).to(3).seconds) def do_it(): print("Hello using schedule library") This can also be used to decorate async functions. In this case the function will be awaited. See Also: @bus.client.every() """ def wrapper(f): coroutine = call_on_schedule( callback=f, schedule=schedule, also_run_immediately=also_run_immediately ) self.add_background_task(coroutine) return f return wrapper # API registration
Example #25
Source File: cron.py From coriolis with GNU Affero General Public License v3.0 | 5 votes |
def _compare(self, pairs): # we don't support the full cron syntax. Either exact matches # or wildcard matches are allowed. Expressions such as: # */10 (every 10 units) # are not supported ret = [] for item in pairs: if item[1] is None or item[0] == item[1]: ret.append(True) else: ret.append(False) return ret
Example #26
Source File: cron.py From coriolis with GNU Affero General Public License v3.0 | 5 votes |
def _janitor(self): # remove expired jobs from memory. The check for expired # jobs runs once every minute. while True: with self._semaphore: tmp = {} for job in self._jobs: if self._jobs[job].is_expired(): LOG.debug("Removing expired job: %s" % job) continue tmp[job] = self._jobs[job] self._jobs = tmp.copy() tmp = None # No need to run very often. Once a minute should do time.sleep(60)
Example #27
Source File: cron.py From coriolis with GNU Affero General Public License v3.0 | 5 votes |
def start(self): schedule.every().minute.do(self._check_jobs) self._eventlets.append(eventlet.spawn(self._loop)) self._eventlets.append(eventlet.spawn(self._janitor)) self._eventlets.append(eventlet.spawn(self._result_loop)) eventlet.spawn(self._ripper)
Example #28
Source File: scheduled_task.py From hproxy with MIT License | 5 votes |
def refresh_task(ver_interval, spider_interval): schedule.every(ver_interval).minutes.do(refresh_proxy) schedule.every(spider_interval).minutes.do(crawl_proxy) while True: schedule.run_pending() time.sleep(1)
Example #29
Source File: main.py From tls-canary with Mozilla Public License 2.0 | 5 votes |
def run(output_directory: str) -> int: tlscanary_binary = "tlscanary" output_directory = os.path.abspath(output_directory) logger.info("Output directory is `%s`" % output_directory) symantec = SymantecJob(tlscanary_binary, os.path.join(output_directory)) tlsdeprecation = TLSDeprecationJob(tlscanary_binary, os.path.join(output_directory)) srcupdate = SrcUpdateJob(tlscanary_binary) # #################################################################### # Here's the the actual schedule ##################################### # #################################################################### schedule.every(60).minutes.do(Scheduler.log_alive) schedule.every().monday.at("00:00").do(symantec.run) schedule.every().wednesday.at("00:00").do(tlsdeprecation.run) schedule.every().saturday.at("00:00").do(srcupdate.run) try: while True: schedule.run_pending() time.sleep(1) except KeyboardInterrupt: logger.critical("\nUser interrupt. Quitting...") return 10
Example #30
Source File: scheduled_task.py From owllook with Apache License 2.0 | 5 votes |
def refresh_task(): schedule.every(CONFIG.SCHEDULED_DICT['SPIDER_INTERVAL']).minutes.do(start_spider) # schedule.every(CONFIG.SCHEDULED_DICT['NOVELS_INTERVAL']).minutes.do(update_all_books_schedule) while True: schedule.run_pending() time.sleep(1)