本文整理汇总了Python中apscheduler.scheduler.Scheduler.start方法的典型用法代码示例。如果您正苦于以下问题:Python Scheduler.start方法的具体用法?Python Scheduler.start怎么用?Python Scheduler.start使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类apscheduler.scheduler.Scheduler
的用法示例。
在下文中一共展示了Scheduler.start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_celery_tasks_status
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def update_celery_tasks_status():
schedudler = Scheduler(daemonic = False)
@schedudler.cron_schedule(second='*/30', max_instances=1)
def update_job():
infos = RedisHelper.get_all_celery_tasks_info()
res_ids = get_tasks_uuid('start_spider')
for res_id in infos:
is_complete = False
info = infos[res_id]
spider_name = RedisStrHelper.split(info)[1]
if res_id in res_ids:
res = app.AsyncResult(res_id)
if res.state == 'SUCCESS':
is_complete = True
else:
if res.state == 'FAILURE':
print res.trackback()
## TODO: warning
pass
RedisHelper.update_celery_task_status(res_id, res.state)
else:
is_complete = True
if is_complete:
if spider_name in source_home_spiders:
# time.sleep(1 * 60)
call(spider_name)
RedisHelper.del_celery_task_status(res_id)
schedudler.start()
示例2: add_job
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def add_job(self, command, hour, minute, sec=0):
logger.info("2. scheduler adding job command: %s at %s:%s:%s" % (
command, hour, minute, sec
))
sched = Scheduler(standalone=True)
#make a db file
shelve.open(
os.path.join(
os.path.dirname(__file__),
'example.db'
)
)
sched.add_jobstore(ShelveJobStore('example.db'), 'shelve')
exec_time = datetime(
date.today().year,
date.today().month,
date.today().day,
int(hour),
int(minute),
int(sec)
)
#test
#exec_time = datetime.now() + timedelta(seconds=5)
sched.add_date_job(
job,
exec_time,
name='alarm',
jobstore='shelve',
args=[command]
)
sched.start()
示例3: main
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def main():
sched = Scheduler()
sched.start()
c_date = datetime.today()
date_ = '2013-11-30'
delay = timedelta(minutes=2)
all_portfolios = combine_lists(PROGRESS_PORTFOLIOS,FIS_GROUP_PORTFOLIOS)
# end of week jobs
#-----------------
if c_date.weekday == 4:
# runs at 6pm Friday evening
sched_date = datetime(c_date.year, c_date.month, c_date.day, 18, 0, 0)
sched.add_date_job(
axys_job,
sched_date,
[MODEL_PORTFOLIOS,all_portfolios,date_])
# monthly jobs
#-------------
if c_date.day == 1:
# runs at 10 am
sched_date = datetime(c_date.year, c_date.month, c_date.day, 10, 0, 0)
sched.add_date_job(
axys_job,
sched_date,
[MODEL_PORTFOLIOS,all_portfolios,date_])
sched_date = sched_date + delay
# keep script 'running' in order to allow the scheduler to stay open and run
# the jobs added
time.sleep(60)
sched.shutdown()
示例4: __init__
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
class BlueprintHandler:
setter_blacklist = []
getter_blacklist = []
def __init__(self, blueprint, testing=False, testing_count=10):
self.blueprint = blueprint
self.testing = testing
self.testing_count = testing_count
self.scheduler = Scheduler()
def do_step(self):
print "stepping"
try:
# Fetch any outstanding events from the engine process and execute in simulator
while not self.local_queue.empty():
action = self.local_queue.get()
try:
self.blueprint.interface.set(action[0], float(action[1]))
print "Received action:", action
except exceptions.ValueError:
print "Value '" + str(action[1]) + "' is not convertable to float"
points = self.blueprint.interface.get_getters()
self.blueprint.step(stepcount=int(1 / 0.1))
g = {}
for point in points:
if point in BlueprintHandler.getter_blacklist:
continue
g[point] = self.blueprint.interface.get(point)
for k in g.keys():
m = Measurement()
m.bid = self.blueprint.building.buildingID
m.timestamp = datetime.utcnow().replace(tzinfo=utc)
m.uuid = k
m.val = g[k]
m.save()
except:
# print 'error: ', sys.exc_info()
print "trace: ", traceback.print_exc()
def init_scheduler(self):
schedule_store = RAMJobStore()
# Write data every 15 seconds.
job_second = self.scheduler.add_interval_job(self.do_step, 0, 0, 0, 0, 15)
schedule_store.add_job(job_second)
self.scheduler.add_jobstore(schedule_store, "Simulator scheduler", quiet=False)
def start(self, queue=None):
self.local_queue = queue
self.init_scheduler()
self.scheduler.start()
def stop(self):
self.scheduler.shutdown()
示例5: load
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def load(self):
sched = Scheduler()
sched.daemonic = False
# Schedules job_function to be run on the third Friday
# of June, July, August, November and December at 00:00, 01:00, 02:00 and 03:00
sched.add_cron_job(self.job_function, second='*/3')
sched.start()
示例6: IntegrationTestBase
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
class IntegrationTestBase(object):
def setup(self):
self.jobstore = self.make_jobstore()
self.scheduler = Scheduler()
self.scheduler.add_jobstore(self.jobstore, 'persistent')
self.scheduler.start()
def test_overlapping_runs(self):
# Makes sure that "increment" is only ran once, since it will still be
# running when the next appointed time hits.
vals = [0]
self.scheduler.add_interval_job(increment, jobstore='persistent', seconds=1, args=[vals, 2])
sleep(2.5)
eq_(vals, [1])
def test_max_instances(self):
vals = [0]
events = []
self.scheduler.add_listener(events.append, EVENT_JOB_EXECUTED | EVENT_JOB_MISSED)
self.scheduler.add_interval_job(increment, jobstore='persistent', seconds=0.3, max_instances=2, max_runs=4,
args=[vals, 1])
sleep(2.4)
eq_(vals, [2])
eq_(len(events), 4)
eq_(events[0].code, EVENT_JOB_MISSED)
eq_(events[1].code, EVENT_JOB_MISSED)
eq_(events[2].code, EVENT_JOB_EXECUTED)
eq_(events[3].code, EVENT_JOB_EXECUTED)
示例7: scheduleNotification
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def scheduleNotification(username, password, receivers, subject, message, attachments, timestring):
logging.basicConfig()
scheduler = Scheduler()
scheduler.start()
sentOn = datetime.datetime.strptime(timestring,"%Y-%m-%dT%H:%M")
scheduler.add_date_job(emailUser,sentOn,[username,password,receivers.split(","),subject,message,attachments])
atexit.register(lambda:scheduler.shutdown(wait=False))
示例8: run_cron_cleanup
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def run_cron_cleanup(settings):
'''
Read cron scheduling entries and schedule
'''
cron_time = {}
year = settings.get("extract.cleanup.schedule.cron.year")
month = settings.get("extract.cleanup.schedule.cron.month")
day = settings.get("extract.cleanup.schedule.cron.day")
week = settings.get("extract.cleanup.schedule.cron.week")
day_of_week = settings.get("extract.cleanup.schedule.cron.day_of_week")
hour = settings.get("extract.cleanup.schedule.cron.hour")
minute = settings.get("extract.cleanup.schedule.cron.minute")
second = settings.get("extract.cleanup.schedule.cron.second")
if year is not None:
cron_time['year'] = year
if month is not None:
cron_time['month'] = month
if day is not None:
cron_time['day'] = day
if week is not None:
cron_time['week'] = week
if day_of_week is not None:
cron_time['day_of_week'] = day_of_week
if hour is not None:
cron_time['hour'] = hour
if minute is not None:
cron_time['minute'] = minute
if second is not None:
cron_time['second'] = second
if len(cron_time) > 0:
sched = Scheduler()
sched.start()
sched.add_cron_job(delete_stats, **cron_time)
示例9: Scheduler
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
class Scheduler(object):
""" The Zato's job scheduler. All of the operations assume the data's being
first validated and sanitized by relevant Zato public API services.
"""
def __init__(self, singleton=None, init=False):
self.singleton = singleton
self.broker_token = None
self.zmq_context = None
self.client_push_broker_pull = None
if init:
self._init()
def _init(self):
self._sched = APScheduler()
self._sched.start()
def wait_for_init(self):
""" Sleeps till the background APScheduler's thread is up and running.
"""
self._init()
while not self._sched.running:
time.sleep(0.01)
def _parse_cron(self, def_):
minute, hour, day_of_month, month, day_of_week = [elem.strip() for elem in def_.split()]
return minute, hour, day_of_month, month, day_of_week
def _on_job_execution(self, name, service, extra, broker_msg_type):
""" Invoked by the underlying APScheduler when a job is executed. Sends
the actual execution request to the broker so it can be picked up by
one of the parallel server's broker clients.
"""
msg = {'action': SCHEDULER.JOB_EXECUTED, 'name':name, 'service': service, 'payload':extra, 'cid':new_cid()}
self.singleton.broker_client.send(msg)
if logger.isEnabledFor(logging.DEBUG):
msg = 'Sent a job execution request, name [{0}], service [{1}], extra [{2}]'.format(
name, service, extra)
logger.debug(msg)
def create_edit(self, action, job_data, broker_msg_type=MESSAGE_TYPE.TO_PARALLEL_ANY):
""" Invokes a handler appropriate for the given action and job_data.job_type.
"""
if logger.isEnabledFor(logging.DEBUG):
logger.debug(job_data)
if not job_data.is_active:
msg = 'Job [{0}] is not active, not scheduling it'.format(job_data.name)
logger.info(msg)
return
handler = '{0}_{1}'.format(action, job_data.job_type)
handler = getattr(self, handler)
try:
handler(job_data, broker_msg_type)
except Exception, e:
msg = 'Caught exception [{0}]'.format(format_exc(e))
logger.error(msg)
示例10: main
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def main(standalone=True):
env.configure("conf.ini")
'''
transfer History Detail for the first time
when program is executed
'''
if env.config.get("transfer_hist_detail_on_loading") and env.config.get("transfer_hist_detail_on_loading") == "1":
transferHistDetails(env.config.get("DB_FILE"), env.config.get("STOREID"),
env.config.get("FTP_HOME"), env.config.get("FTP_HOST"),
env.config.get("FTP_PORT"), env.config.get("FTP_USERNAME"),
env.config.get("FTP_PASSWORD"))
'''
create the scheduler for two job:
1. check the client's alive
2. transfer details to server
'''
scheduler = Scheduler(standalone=standalone)
scheduler.add_interval_job(sync,
minutes=int(env.config.get("sync_interval")),
args=(env.config.get("DB_FILE"), env.config.get("STOREID"),
env.config.get("PROGNAME"), env.config.get("PROG"),
env.config.get("FTP_HOME"), env.config.get("FTP_HOST"),env.config.get("FTP_PORT"),
env.config.get("FTP_USERNAME"),env.config.get("FTP_PASSWORD")))
scheduler.add_cron_job(transferFluxDetailsByStatus,
day_of_week=env.config.get("upload_day_of_week"), hour=env.config.get("upload_hour"), minute=env.config.get("upload_minute"),
args=(env.config.get("DB_FILE"), env.config.get("STOREID"),
env.config.get("FTP_HOME"), env.config.get("FTP_HOST"),env.config.get("FTP_PORT"),
env.config.get("FTP_USERNAME"),env.config.get("FTP_PASSWORD"),
0))
scheduler.start()
示例11: main
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def main():
config_file = "config.xml"
xml = ET.parse(config_file)
HOST_NAME = xml.find('host_name').text
DB_NAME = xml.find('db_name').text
DISPLAY_ADDR = xml.find("display_addr").text
DISPLAY_PORT = int(xml.find('display_port').text)
ENDPOINT = xml.find("endpoint").text
SECONDS = int(xml.find("seconds").text)
USERNAME = xml.find("username").text
PASSWORD = xml.find("password").text
HOST = 'http://'+ USERNAME+ ':'+ PASSWORD + '@'+ HOST_NAME
print "starting ..."
#print HOST, DB_NAME, DISPLAY_ADDR, DISPLAY_PORT
#readData(HOST, DB_NAME, DISPLAY_ADDR, DISPLAY_PORT)
display = LedDisplay(HOST, DB_NAME, DISPLAY_ADDR, DISPLAY_PORT, ENDPOINT)
# Start the scheduler
sched = Scheduler()
sched.add_interval_job(display.query, seconds=SECONDS )
sched.start()
try:
while True:
time.sleep(0.1)
except KeyboardInterrupt:
print "terminating"
sched.shutdown()
示例12: pre_eva_start
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def pre_eva_start(self, conf):
# Load all jobs
self.invoke('pre_scheduler_load_jobs')
sched = APScheduler()
conf['scheduler']['scheduler'] = sched
for job_name in conf['scheduler']['jobs']:
job = conf['scheduler']['jobs'][job_name]
if job.get('type') == 'date':
# datetime is a datetime string in this case
# ie: '2012-11-06 14:25:10.8880'
sched.add_date_job(job['func'], job['datetime'], args=[conf])
elif job.get('type') == 'interval':
sched.add_interval_job(job['func'],
seconds=job['interval'].get('seconds', 0),
minutes=job['interval'].get('minutes', 0),
hours=job['interval'].get('hours', 0),
days=job['interval'].get('days', 0),
weeks=job['interval'].get('weeks', 0),
start_date=job['interval'].get('start_date'),
args=[conf])
elif job.get('type') == 'cron':
sched.add_cron_job(job['func'],
second=job['interval'].get('second'),
minute=job['interval'].get('minute'),
hour=job['interval'].get('hour'),
day=job['interval'].get('day'),
week=job['interval'].get('week'),
month=job['interval'].get('month'),
year=job['interval'].get('year'),
day_of_week=job['interval'].get('day_of_week'),
args=[conf])
sched.start()
self.invoke('post_scheduler_load_jobs')
示例13: main
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def main():
log.info( "BLI Monitor starting..." )
#check_pid()
bli = BLIMonitor()
spot = SpotMonitor()
sched = Scheduler(daemonic = False)
#sched.add_listener(err_listener, events.EVENT_ALL)
sched.add_interval_job(lambda:bli.check(), seconds=3)
sched.add_interval_job(lambda:spot.check(), seconds=3)
sched.add_listener(err_listener, events.EVENT_JOB_ERROR | events.EVENT_JOB_EXECUTED| events.EVENT_JOB_MISSED)
sched.start()
log.info( "started" )
"""
while 1:
time.sleep(2)
monitor.check()
"""
pass
示例14: handle
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
def handle(self, *args, **options):
sched = Scheduler()
sched.start()
from twilio.rest import TwilioRestClient
account_sid = "AC6fe90756ae4096c5bf790984038a3f32"
auth_token = "97e8833ee3553bc4d9d16e86f1865d32"
client = TwilioRestClient(account_sid, auth_token)
for user in user_list:
user_schedule = Schedule.objects.all().filter(user=user)
for schedule in user_schedule:
day_of_week = schedule.day_of_week
hour = schedule.hour
minute = schedule.minute
user_message = schedule.message
print 'BEFORE:' + str(user_message)
def timed_job(msg):
print 'AFTER' + str(msg)
sched.add_cron_job(lambda: timed_job(user_message), second='0-60')
#sched.start()
print 'test'
while True:
pass
示例15: Wikipedia
# 需要导入模块: from apscheduler.scheduler import Scheduler [as 别名]
# 或者: from apscheduler.scheduler.Scheduler import start [as 别名]
class Wikipedia(Plugin):
def __init__(self, skype):
super(Wikipedia, self).__init__(skype)
self.daily_channels = ["#stigrk85/$jvlomax;b43a0c90a2592b9b"]
self.sched = Scheduler()
self.sched.start()
self.command = "wikipedia"
self.sched.add_cron_job(self.dailyWikipedia, hour=18, minute=0, day_of_week="mon-sun")
def message_received(self, args, status, msg):
if (len(args) == 1 and args[0] == "random") or not args:
url = self.fetch_randWiki()
msg.Chat.SendMessage(url)
else:
try:
page = wiki.wikipedia.page(" ".join(args))
if page.url:
msg.Chat.SendMessage(urllib.unquote(page.url))
else:
msg.Chat.SendMessage("Could not find any results for {}".format(" ".join(args)))
except wiki.exceptions.DisambiguationError:
msg.Chat.SendMessage("Your search is disambiguous")
except wiki.exceptions.PageError:
msg.Chat.SendMessage("Could not find any results for {}".format(" ".join(args)))
def fetch_randWiki(self):
r = requests.get("http://en.wikipedia.org/wiki/Special:Random")
return r.url
def dailyWikipedia(self):
for channel in self.daily_channels:
chat = self.skype.Chat(channel)
chat.SendMessage("Dagens random wikipedia: " + self.fetch_randWiki())