def test_base_case(self): cron = Cron() cron.schedule( Tab('two_sec', verbose=False).every(seconds=2).run(time_logger, 'two_sec'), Tab('three_sec', verbose=False).every(seconds=3).run(time_logger, 'three_sec')) with PrintCatcher(stream='stdout') as stdout_catcher: cron.go(max_seconds=6) base_lookup = { 'three_sec': 3, 'two_sec': 2, } lines = list(stdout_catcher.text.split('\n')) # make sure times fall int right slots for line in lines: if line: words = line.split() name = words[0] time = parse('T'.join(words[1:])) self.assertEqual(time.second % base_lookup[name], 0) # make sure the tasks were run the proper number of times counter = Counter() for line in lines: if line: counter.update({line.split()[0]: 1}) self.assertEqual(counter['two_sec'], 3) self.assertEqual(counter['three_sec'], 2)
def test_non_robust_case(self): then = datetime.datetime.now() def timed_error(): now = datetime.datetime.now() if then + datetime.timedelta( seconds=3) < now < then + datetime.timedelta(seconds=6): print('timed_error_failure') raise ExpectedException( 'This exception is expected in tests. Don\'t worry about it.' ) else: print('timed_error_success') cron = Cron() cron.schedule( Tab('one_sec', verbose=False).every(seconds=1).run(time_logger, 'running_time_logger'), Tab('two_sec', verbose=False, robust=False).every(seconds=1).run(timed_error)) with PrintCatcher(stream='stdout') as catcher: cron.go(max_seconds=10) success_count = catcher.text.count('timed_error_success') failure_count = catcher.text.count('timed_error_failure') time_logger_count = catcher.text.count('running_time_logger') self.assertEqual(success_count, 3) self.assertEqual(failure_count, 1) self.assertEqual(time_logger_count, 10)
def test_tab_loop(self): tab = Tab('one_sec', verbose=False).every(seconds=1).run(time_logger, 'one_sec') with PrintCatcher() as catcher: tab._loop(max_iter=3) self.assertEqual(catcher.text.count('one_sec'), 3)
def test_tab_loop_anchored(self): now = datetime.datetime.now() + datetime.timedelta(seconds=1) tab = Tab('one_sec', verbose=False).every(seconds=1).starting(now).run( time_logger, 'one_sec') with PrintCatcher() as catcher: tab._loop(max_iter=3) self.assertEqual(catcher.text.count('one_sec'), 3)
def test_non_robust_case(self): then = datetime.datetime.now() cron = Cron() cron.schedule( Tab('one_sec', verbose=False).every(seconds=1).run(time_logger, 'running_time_logger'), Tab('two_sec', verbose=False, robust=False).every(seconds=1).run( functools.partial(timed_error, then))) with PrintCatcher(stream='stdout') as catcher: cron.go(max_seconds=10) success_count = catcher.text.count('timed_error_success') failure_count = catcher.text.count('timed_error_failure') time_logger_count = catcher.text.count('running_time_logger') self.assertEqual(success_count, 3) self.assertEqual(failure_count, 1) self.assertEqual(time_logger_count, 10)
def test_anchored_case(self): cron = Cron() starting = datetime.datetime.now() cron.schedule( Tab('three_sec', verbose=False).starting(starting).every(seconds=3).run( time_logger, 'three_sec'), Tab('three_sec_str', verbose=False).starting(starting.isoformat()).every( seconds=3).run(time_logger, 'three_sec_str'), ) with PrintCatcher(stream='stdout') as stdout_catcher: cron.go(max_seconds=3.5) # make sure times fall int right slots lines = list(stdout_catcher.text.split('\n')) for line in lines: if line: words = line.split() time = parse('T'.join(words[1:])) elapsed = (time - starting).total_seconds() self.assertTrue(elapsed < 3)
def test_excluding(self): # Test base case cron = Cron() cron.schedule( Tab('base_case', verbose=True).every(seconds=1).run(time_logger, 'base_case'), Tab('d+').every(seconds=1).during(return_true).run( time_logger, 'd+'), Tab('d-').every(seconds=1).during(return_false).run( time_logger, 'd-'), Tab('e+').every(seconds=1).excluding(return_true).run( time_logger, 'e+'), Tab('e-').every(seconds=1).excluding(return_false).run( time_logger, 'e-'), ) with PrintCatcher(stream='stdout') as stdout_catcher: cron.go(max_seconds=2) self.assertTrue('d+' in stdout_catcher.text) self.assertFalse('d-' in stdout_catcher.text) self.assertFalse('e+' in stdout_catcher.text) self.assertTrue('e-' in stdout_catcher.text)
def test_starts_on_next(self): second = 0 interval_seconds = 5 while second % interval_seconds == 0: now = datetime.datetime.now() second = now.second epoch = fleming.floor(now, second=interval_seconds) then = epoch + relativedelta(seconds=interval_seconds) cron = Cron().schedule( Tab( name='pusher', robust=False, memory_friendly=False, ).run(func, ).starting(then).every(seconds=5)) with PrintCatcher(stream='stdout') as catcher: cron.go(max_seconds=5) assert ('func_was_called' in catcher.text)
from crontabs import Cron, Tab import time import datetime from datetime import timedelta import sys import os def my_job(name): task = 'arank.py' if len(sys.argv) == 3: startTime = sys.argv[1] endTime = sys.argv[2] task = 'arank.py ' + startTime + ' ' + endTime elif len(sys.argv) == 2: startTime = sys.argv[1] endTime = datetime.datetime.now().strftime('%Y-%m-%d') task = 'arank.py ' + startTime + ' ' + endTime else: endTime = datetime.datetime.now().strftime('%Y-%m-%d') task = 'arank.py ' + endTime print('task', task) os.system("python3 {}".format(task)) if __name__ == '__main__': Cron().schedule( Tab(name='forever').run(my_job, 'my_func').every(seconds=30), ).go()
def test_robust_error(self): tab = Tab('one_sec', verbose=False).every(seconds=1).run(error_raisor, 'one_sec') tab._loop(max_iter=1)
def test_incomplete(self): with self.assertRaises(ValueError): Cron().schedule(Tab('a').run(time_logger, 'bad')).go()
def __create_uploading_job(self): return Tab(name='uploading_job').every(days=1).during( self.__uploading_time).run(self.__uploading_operation)
#! /usr/bin/env python # flake8: noqa from crontabs import Cron, Tab from datetime import datetime def my_job(*args, **kwargs): print('args={} kwargs={} running at {}'.format(args, kwargs, datetime.now())) Cron().schedule( Tab(name='future_job').every( seconds=5).starting_at('12/27/2017 16:55').run( my_job, 'fast', seconds=5)).go(max_seconds=60) # from crontabs.crontabs import Cron, Tab # import datetime # # # def func(n, extra=''): # print('func {}.{} {}'.format(n, extra, datetime.datetime.now())) # # # cron = Cron() # # tabs = [ # Tab(str(n)).every(seconds=n).run(func, n) # for n in range(1, 8) # ]
print(e) f.close() if cache_ip != real_ip: req = urllib2.Request(api_url + 'dnsListRecords?version=1&type=xml&key=' + api_key + '&domain=' + domain_name, headers={'User-Agent': "Magic Browser"}) r = urllib2.urlopen(req).read() dns_list_tree = ET.fromstring(r) record = [x for x in dns_list_tree[1] if len(x) >= 3 and x[2].text == host_name] record_id = record[0][0].text req = urllib2.Request(api_url + 'dnsUpdateRecord?version=1&type=xml&key=' + api_key + '&domain=' + domain_name + '&rrid=' + record_id + '&rrhost=' + rrhost + '&rrvalue=' + real_ip + '&rrttl=7207', headers={'User-Agent': "Magic Browser"}) print(urllib2.urlopen(req).read()) with open(filename, 'w+') as f: f.write(json.dumps({ "address": real_ip })) f.close() else: print('ip not change') update() Cron().schedule( Tab(name='run_my_job').every(minutes=time_interval).run(update) ).go()
task = 'ceshi.py' os.system("python3 {}".format(task)) def ceshi2_job(name): task = 'ceshi2.py' os.system("python3 {}".format(task)) def my_job(name): print('Running function with name={}'.format(name)) if __name__ == '__main__': # # All logging messages are sent to sdtout # Cron().schedule( # # Turn off logging for job that runs every five seconds # Tab(name='my_fast_job', verbose=False).run(dcenter_job, 'fast', seconds=5), # # Go ahead and let this job emit logging messages # Tab(name='my_slow_job').run(ceshi_job, 'slow', seconds=20), # Tab(name='my_slow_job').run(ceshi1_job, 'slow', seconds=20), # ).go() Cron().schedule( Tab(name='one').run(dcenter_job, 'dcenter_job').every(seconds=5), Tab(name='two').run(ceshi_job, 'ceshi_job').every(seconds=80), ).go()
def test_non_robust_error(self): tab = Tab('one_sec', verbose=False, robust=False).every(seconds=1).run(error_raisor, 'one_sec') with self.assertRaises(ExpectedException): tab._loop(max_iter=1)
def test_bad_starting(self): with self.assertRaises(ValueError): Tab('a').starting(2.345)
def test_bad_every(self): with self.assertRaises(ValueError): Tab('a').every(second=1, minute=3)
def test_bad_interval(self): with self.assertRaises(ValueError): Tab('a').every(bad=11)
""" from crontabs import Cron, Tab from datetime import datetime from helper import helper import subprocess # cron job defination args def my_job(*args, **kwargs): running = helper.generate_file_name('pods_running') failed = helper.generate_file_name('pods_failed') succeeded = helper.generate_file_name('pods_succeeded') subprocess.run(['curl', 'http://localhost:8000/push_to_object_store'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) response = subprocess.run([ 'python', './interface/interface_push.py', running, failed, succeeded ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print('args={} kwargs={} running at {}'.format(args, kwargs, datetime.now())) print(response) # will run with a specified interval synced to the top of the minute Cron().schedule( Tab(name='run_my_job').every(seconds=60).run(my_job, 'my_arg', my_kwarg='hello')).go()
receiver_addr = "" email="" password="" #msg information body="Hello. These are today's video data." link = MIMEText(u'<a href="www.google.com">This is the link to the data</a>', 'html') #Scheduling the running of program using crontabs Cron().schedule( Tab( name='send_email' ).run( send_email, sender_addr, receiver_addr, body, link ).every( day=1 ).starting( '08/15/2020 08:00' ).until( '11/20/2020 08:00' ) ).go() #Credit to the creator of crontabs #The MIT License (MIT) #Copyright (c) 2017 Rob deCarvalho #Permission is hereby granted, free of charge, to any person obtaining a copy of #this software and associated documentation files (the "Software"), to deal in #the Software without restriction, including without limitation the rights to