def cmd_start(self): from apscheduler.schedulers.background import BlockingScheduler sched = BlockingScheduler() with transaction.manager: Scheduler.add_all_to_apscheduler(sched, DbSession, user=SYSTEM_UID, begin_transaction=True) sched.start() sched.print_jobs()
def auto_water(): with open('watering_parameters.txt') as handle: wp = json.loads(handle.read()) with open("next_water.txt", "w+") as f1: f1.write("Watering twice a day at " + str(wp["first_water"]) + ":00 and at " + str(wp["second_water"]) + ":00 for " + str(wp["watering_time"]) + " seconds") update_logbook("Started auto watering") global scheduler scheduler = BlockingScheduler() scheduler.add_job(pump_on, 'cron', day_of_week='mon-sun', hour=wp["first_water"], id='first_water') scheduler.add_job(pump_on, 'cron', day_of_week='mon-sun', hour=wp["second_water"], id='second_water') scheduler.print_jobs() scheduler.start() return
job2 = sched.add_job(job_fun, 'interval', start_date='2017-06-19 10:42:40', coalesce=True, seconds=5) ''' # TODO 计划任务 2017-6-19 10:27:30 job = sched.add_job(job_fun, 'date', run_date=datetime(2017, 6, 19, 10, 27, 30),args=['this is date job']) ''' ''' # TODO 计划任务 周一到周五21:39执行 2017-6-30开始,2017-9-30停止 job = sched.add_job(job_fun, 'cron', day_of_week='mon-fri', hour=21, minute=39, start_date='2017-06-30' ,end_date='2017-09-30') ''' #TODO 获得任务属性和状态 sched.print_jobs() #TODO 获得任务id和执行函数 print(sched.get_jobs()) #TODO 删除任务不执行 #job.remove() ''' #TODO 暂停以及恢复任务 job2.pause() job2.resume() ''' print("press Ctrl+{} TO STOP TASK".format('break' if platform.system() == 'Windows' else 'C')) try: sched.start() except (SyntaxWarning, BlockingIOError, SystemError) as e: print(e)
class JobLauncher(object): def __init__(self, background=False, deamon=True, **kwargs): logging.basicConfig(format="[%(asctime)s] %(message)s", atefmt="%Y-%m-%d %H:%M:%S") logging.getLogger('apscheduler').setLevel(logging.DEBUG) if background: self.sched = BackgroundScheduler(deamon=deamon) # background else: self.sched = BlockingScheduler(deamon=deamon) # foreground # TODO: Read from configuration file. self.sched.configure( jobstores={ # "sqlite": SQLAlchemyJobStore(url='sqlite:///app/database/example.db'), # "default": MemoryJobStore() "default": SQLAlchemyJobStore(url='sqlite:///app/database/example.db') }, executors={ 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) }, job_defaults={ 'coalesce': False, 'max_instances': 3 }, timezone=get_localzone() # Asia/Seoul ) self.retried = 0 self.logger = logging.getLogger('apscheduler') super(JobLauncher, self).__init__() def start(self): try: if self.sched.state != STATE_RUNNING: self.printJobs(jobstore='default') started = self.sched.start() except ConflictingIdError as e: traceback.print_exc() except KeyboardInterrupt as e: traceback.print_exc() finally: pass # Remove all remained store. # self.sched.remove_all_jobs() # for job in self.getJobs(): # if job.pending: # job.pause() self.logger.info('Finished') self.logger.info(self.getJobs()) self.printJobs() def stop(self, wait=False): if self.sched.state == STATE_RUNNING: self.sched.shutdown(wait=wait) def resume(self): if self.sched.state == STATE_RUNNING: self.sched.resume() def pause(self): if self.sched.state == STATE_RUNNING: self.sched.pause() def addListener(self, listener, types): self.sched.add_listener(listener, types) def addJob(self, job, **kwargs): execute, trigger, options = job.build(**kwargs) added_job = self.sched.add_job(execute, trigger, **options) self.printJobs() return added_job def getJob(self, job_id): return self.sched.get_job(job_id) def getJobs(self, jobstore=None): return self.sched.get_jobs(jobstore=jobstore) def removeJob(self, job_id, jobstore=None): return self.sched.remove_job(job_id, jobstore=jobstore) def removeAllJob(self, jobstore=None): return self.sched.remove_all_jobs(jobstore=jobstore) def printJobs(self, jobstore=None, out=None): return self.sched.print_jobs(jobstore=jobstore, out=None) def getJobState(self, job_id=None, jobstore=None): state = list() if job_id is not None: job = self.sched.get_job(job_id, jobstore=jobstore) if job is not None: temp = dict() temp[job.id] = { "next_run_time": job.next_run_time, "state": job.pending, } state.append(temp) else: for job in self.sched.get_jobs(jobstore=jobstore): temp = dict() temp[job.id] = { "next_run_time": job.next_run_time, "state": job.pending, } state.append(temp) return state
logging.info("""hello-world.py This basic example prints the text "Hello World" in the middle of the LCD Press any button to see its corresponding LED toggle on/off. Press Ctrl+C to exit. """) config = config.config() #scheduler = BackgroundScheduler() scheduler = BlockingScheduler() display = clockDisplay.clockDisplay() buttons = buttonActions.buttonActions(config,display) # start by displaying the minutes... display.drawTime() # Now schedule a job to update every minute logging.info("Setting scheduler") job = scheduler.add_job(display.drawTime, trigger='cron', minute='*') scheduler.print_jobs() logging.info("Pausing main thread by starting blocking scheduler") scheduler.start() logging.info("Whoops.... schduler.start didn't block")