def schedule_queries(_id, trip_array): #_id: This is the original trip _id #start, end must both be represented as strings which contain the latitude and longitude of the location #purturbed_time must be a datetime object. #start/end: 'lat1,lon1' #example location input: '-33.8674869,151.2069902' #example use case: #schedule_query(start='-33.8674869,151.2069902', end='-33.8674869,151.2069902', time=datetime.datetime.now() + datetime.timedelta(days=10)) #TODO: write regex to enforce that passed in locations are geocoded; i.e. lat1,lon1, lat2,lon2 #TODO: this will run every year, need to figure out if python crontab can support yearly configuration so it only runs once for trip in trip_array: start = trip.get_start_coordinates() end = trip.get_end_coordinates() time = trip.get_time() cron = CronTab() exec_str = python_location + ' ' + query_script_location + ' ' + _id job = cron.new(command=exec_str) job.month.on(perturbed_time.month) job.day.on(perturbed_time.day) job.hour.on(perturbed_time.hour) job.minute.on(perturbed_time.minute) job.enable() cron.write() print("You have successfully scheduled this CRON job.")
def schedule(self): cron = CronTab() for schedule in self.collection.find(): job = cron.new(command='python /backyarbarber/python/controller.py startMower') min = schedule["time"]["minute"] hour = schedule["time"]["hour"] days = schedule["days"] dayString = "" if days["Sunday"]: dayString += ",0" elif days["Monday"]: dayString += ",1" elif days["Tuesday"]: dayString += ",2" elif days["Wednesday"]: dayString += ",3" elif days["Thursday"]: dayString += ",4" elif days["Friday"]: dayString += ",5" elif days["Saturay"]: dayString += ",6" if dayString[0] == ',': dayString = dayString[1:] job.minute.on(min) job.hour.on(hour) job.days.on(dayString) job.enable()
def build_cron_job(jobs, dest_d=None): from crontab import CronTab tabfile = os.path.join(BASE_DIR if dest_d is None else dest_d, "cron.tab") cron = CronTab() try: for j in jobs: if j['unit'] not in cron_units: continue if 'frequency' not in j.keys(): continue job = cron.new( command=j['command'], comment=j['comment']) if j['unit'] in ["mins", "minutes", "min", "minute"]: job.every(j['frequency']).minutes() elif j['unit'] in ["hours", "hour"]: job.every(j['frequency']).hours() elif j['unit'] in ["days", "day"]: job.every(j['frequency']).days() cron.write(tabfile) return True except Exception as e: print e, type(e) return False
def run(self): """default method""" sess = Session() sender = self.req_obj.get('sender', '') #exctract sender email email = sender.split('/')[0] #find user profile by primary email profile = sess.query(Profile).filter(Profile.email == email).one() cron = CronTab(getuser()) msg = '' job = cron.new(command='/usr/bin/python %s/core/cron/cronjob.py --uuid=%s --cmd="check my sites" --arguments="%s"' % (ROBOT_DIR, profile.uuid, msg.replace('"', ''))) #every hour job.minute.on(0) cron.write() response = 'ok, cronjob added %s' % job.render() if self.req_from == 'jabber': todo = {'text': response, 'jmsg': response, 'type': 'response'} self.response = todo if self.req_from == 'julius': bang() todo = {'say': response, 'text': response, 'type': 'response'} self.response = say(self.request.replace('say', '').upper()) return self.response
def delete_job(self, cron_id=None): cron = CronTab(user=True) jobs = self.get_cron_job(cron_id, cron=cron) for job in jobs: cron.remove(job) cron.write() return jobs
def new_job(self, folder=None, minute=None, hour=None, month=None, day_of_month=None, day_of_week=None): cron = CronTab(user=True) fileName = "%s.jpg" % (strftime("%Y-%m-%d %I.%M.%S %pe")) if folder is None: folder = "images" cmd = "raspistill -vf -hf -o %s/%s/$(date '+%%m-%%d-%%y_%%H:%%M:%%S').jpg" % (getcwd(), folder) if minute is None and hour is None and month is None and day_of_month is None and day_of_week is None: call(cmd) return None else: while True: cron_id = '%04d' % randint(0,9999) conflicting_cron_jobs = self.get_cron_job(cron_id) if len(conflicting_cron_jobs) == 0: break job = cron.new(command=cmd,comment="%s%s" % (self.comment_prefix, cron_id)) if minute is None: minute = "*" if hour is None: hour = "*" if month is None: month = "*" if day_of_month is None: day_of_month = "*" if day_of_week is None: day_of_week = "*" job.setall(minute, hour, day_of_month, month, day_of_week) cron.write() return job
def servicesStart(): cron = CronTab(user=True) for job in cron.find_comment('polis'): if job.comment == 'polis': print("**WARNING: Polis services already running -- run 'polis stop'", file=sys.stderr) sys.exit(2) for i in range(len(SOURCES)): root_dir = ROOT_DIR logfile = SOURCES[i]["LOGFILE"] daemon = SOURCES[i]["DAEMON"] freq = SOURCES[i]["FREQ"] command_string = "python " + root_dir + "/python/" + daemon + " > " + logfile + " 2>&1" job = cron.new(command=command_string, comment='polis') try: # first entry set to 0 -- otherwise a new script spawns every minute job.setall("0 %s * * *" % freq) except: print("**ERROR: Could not set %s" % daemon, file=sys.stderr) print("Check config.py for invalid frequency settings", file=sys.stderr) sys.exit(3) for job in cron: if job.is_valid(): print(job.command) else: print("**ERROR: Invalid job: %s" % job.command) sys.exit(4) # assuming all goes well: cron.write()
def install_buildbot_slave(name, path=None, script_dir='', shell=False, **args): username = '******' if platform.system() == 'Linux': # Create buildbot user if it doesn't exist. username = '******' import pwd try: pwd.getpwnam(username) except KeyError: check_call(['sudo', 'useradd', '--system', '--home', '/var/lib/buildbot', '--create-home', '--shell', '/bin/false', 'buildbot']) path = path or os.path.expanduser('~{0}/slave'.format(username)) if os.path.exists(path): return pip_install('buildbot-slave', 'buildbot') # The password is insecure but it doesn't matter as the buildslaves are # not publicly accessible. command = [os.path.join(script_dir, 'buildslave'), 'create-slave', path, args.get('ip', '10.0.2.2'), name, 'pass'] if not windows: command = ['sudo', '-u', username] + command check_call(command, shell=shell) if windows: return if args.get('nocron', False): return pip_install('python-crontab', 'crontab') from crontab import CronTab cron = CronTab(username) cron.new('PATH={0}:/usr/local/bin buildslave start {1}'.format( os.environ['PATH'], path)).every_reboot() cron.write() # Ignore errors from buildslave as the buildbot may not be accessible. call(['sudo', '-H', '-u', username, 'buildslave', 'start', path])
def add_system_cron(self, **kwargs): cronfile = kwargs.get("filename", "/etc/crontab") cron = CronTab(tabfile=cronfile, user=False) job = self.add_cron_command(cron, **kwargs) job.user = "******" cron.write() return True
def time_change(message): hour, minute = message["data"].split(":") print("New wake up time: {}-{}".format(hour, minute)) TEST = True if TEST: cron = CronTab(tabfile="test.CronTab") else: cron = CronTab(user=True) # get already created crontab for job in cron.find_comment("clock weekday"): print(job) if job.hour == hour and job.minute == minute: pass else : #remove old cron cron.remove_all(comment="clock weekday") job = cron.new(command="python /home/pi/sunlight_alarm_clock/light/python/transition.py", comment='clock weekday') job.hour.on(hour) job.minute.on(minute) schedule = job.schedule(date_from=datetime.now()) if TEST: cron.write("test.CronTab") else: cron.write()
def test_insert(self): '''Insert a job, It should insert a job and return it with id''' result = self.schedule.insert({ "enable": 1, "alias": "reboot", "command": "uptime && test_insert", "schedule": "0 0 * * *", "executer": True }) self.assertDictEqual({ "id": 2, "enable": 1, "alias": "reboot", "command": "uptime && test_insert", "schedule": "0 0 * * *", "executer": True, "comment": "sanji_schedule_2" }, result) jobs = [] cron = CronTab(user=True) for job in cron.find_comment("sanji_schedule_2"): jobs.append(job) self.assertEqual(len(jobs), 1)
def linuxLoadCronServices(service): from crontab import CronTab cron = CronTab() if service == "MPPatchLoader": print("Loading MPPatchLoader") cmd = MP_SRV_CONF + '/scripts/MPSUSPatchSync.py --config ' + MP_SRV_BASE + '/etc/patchloader.json' job = cron.new(command=cmd) job.set_comment("MPPatchLoader") job.hour.every(8) job.enable() cron.write_to_user(user='******') if service == "MPSyncContent": print("Loading MPSyncContent") cmd = MP_SRV_CONF + '/scripts/MPSyncContent.py --config ' + MP_SRV_BASE + '/etc/syncContent.json' job = cron.new(command=cmd) job.set_comment("MPSyncContent") job.minute.every(30) job.enable() cron.write_to_user(user='******') if service == "MPAVLoader": print("Loading MPAVLoader") cmd = MP_SRV_CONF + '/scripts/MPAVDefsSync.py --config ' + MP_SRV_BASE + '/etc/avconf.json' job = cron.new(command=cmd) job.set_comment("MPAVLoader") job.hour.every(11) job.enable() cron.write_to_user(user='******')
def test_update(self): '''Update a job, It should update a job and return it''' added = self.schedule.get()[0] result = self.schedule.update({ "id": added["id"], "enable": 1, "alias": "uptime", "command": "uptime && test_update", "schedule": "1 1 1 * *", "executer": True }) self.assertNotEqual(result, None) self.assertDictEqual({ "id": added["id"], "enable": 1, "alias": "uptime", "command": "uptime && test_update", "schedule": "1 1 1 * *", "executer": True, "comment": added["comment"] }, result) jobs = [] cron = CronTab(user=True) for job in cron.find_comment(result["comment"]): jobs.append(job) self.assertEqual(job.slices, result["schedule"]) self.assertEqual(job.command, result["command"]) self.assertEqual(len(jobs), 1)
def cleanScheduledPolicies(args): """ Remove expired (or all) policies from crontab """ debug = args.verbose config = ConfigLoader(args.config) setLoggingSystem(config, debug) logger.info('Start to remove old policies') cron = CronTab(user=True) jobList = [] for job in cron: logger.debug('checking job command: %s', job.command) if job.command.startswith("export clientUserName") \ and 'irule' in job.command: if (args.all): jobList.append(job) else: logger.debug('checking if the job is expired') schedule = job.schedule() datetime = schedule.get_next() if datetime.year > (date.today()).year: logger.debug('removing the expired job') jobList.append(job) for job in jobList: logger.info('removing the job ' + job.comment) cron.remove(job) cron.write_to_user(user=True) logger.info('Policies removed')
def run(self): """default method""" sess = Session() sender = self.req_obj.get('sender', '') #exctract sender email email = sender.split('/')[0] #find user profile by primary email profile = sess.query(Profile).filter(Profile.email == email).one() cron = CronTab('smarty') job = cron.new( command='/usr/bin/python %s/cron/cronjob.py --uuid=%s ' % ( ROBOT_DIR, profile.uuid )) logger.info('show cronjob %s' % cron.render() ) list = cron.find_command( '--uuid=%s' % profile.uuid ) response = 'all my cronjobs' for job in list: response += "\n" + job if self.req_from == 'jabber': todo = { 'text' : response, 'jmsg' : response, 'type': 'response' } self.response = todo if self.req_from == 'julius': bang() todo = { 'say': response , 'text' : response ,'type': 'response' } self.response = say(self.request.replace('say', '').upper()) return self.response
def updateCrontabInterval(): crontab = CronTab() crontabEntries = crontab.find_command(commandPath) if len(crontabEntries) > 1: raise Exception("more than one entry in the crontab!?") elif len(crontabEntries) == 1: updateIntervalString = downloadConfigUrl("http://%s/%s.config?type=updinterval" % (server, branchName)) updateIntervalString = updateIntervalString[6:-4] updateInterval = int(updateIntervalString) if updateInterval < 5 or updateInterval > 480: raise Exception("received corrupt update interval") logInfo("update interval will be set to: " + str(updateInterval) + " mins") crontabEntry = crontabEntries[0] crontabEntry.clear() if updateInterval > 59: crontabEntry.hour().every(updateInterval / 60) crontabEntry.minute().on(random.randint(0, 59)) else: crontabEntry.minute().every(updateInterval) logDebug("Will write new crontab '" + unicode(crontab.render()) + "'") crontab.write() else: logInfo("we are not installed in crontab, update interval will not be updated")
class CompatTestCase(unittest.TestCase): """Test basic functionality of crontab.""" def setUp(self): self.crontab = CronTab(tab=INITAL_TAB) def test_00_enabled(self): """Test Compatability Mode""" self.assertTrue(SunOS) def test_01_addition(self): """New Job Rendering""" job = self.crontab.new('addition1') job.minute.during(0, 3) job.hour.during(21, 23).every(1) job.dom.every(1) self.assertEqual(job.render(), '0,1,2,3 21,22,23 * * * addition1') def test_02_addition(self): """New Job Rendering""" job = self.crontab.new(command='addition2') job.minute.during(4, 9) job.hour.during(2, 10).every(2) job.dom.every(10) self.assertNotEqual(job.render(), '4-9 2-10/2 */3 * * addition2') self.assertEqual(job.render(), '4,5,6,7,8,9 2,4,6,8,10 1,11,21,31 * * addition2')
def linux_createCronJobs(): #start cronjob cron_client = CronTab() iter = cron_client.find_comment("Desktop Image Changer client") try: print "Client Cron Task Found" iter.next() except StopIteration: print 'Installing Client Cron Task' job = cron_client.new(scriptDirectory+ "/client.py dailyUpdate", comment="Desktop Image Changer client") job.every().dom() cron_client.write() cron_daemon = CronTab() iter = cron_daemon.find_comment("Desktop Image Changer daemon") try: print "Daemon Cron Task Found" iter.next() except StopIteration: print 'Installing Daemon Cron Task' job = cron_daemon.new(scriptDirectory+ "/daemon.py &", comment="Desktop Image Changer daemon") job.every_reboot() cron_daemon.write()
def test_timezones(self): s = CronTab('0 9 13 3 * 2016') self.assertEqual(s.next(datetime.datetime(2016, 3, 13), default_utc=True), 32400) self.assertEqual(s.next(pytz.utc.localize(datetime.datetime(2016, 3, 13)), default_utc=True), 32400) self.assertEqual(s.next(pytz.timezone('US/Eastern').localize(datetime.datetime(2016, 3, 13))), 28800)
def cleanScheduledPolicies(policyId, logger): """ Remove policies from crontab @type policy: policy object @param policy: The policy to be scheduled @type logger: logger type @param logger: The logger """ logger.info('Start to remove scheduled policies') cron = CronTab(user=True) jobList = [] for job in cron: logger.debug('checking job command: %s', job.command) # find the scheduled cron jobs based on iRODS icommand keywords if job.command.startswith("export clientUserName") \ and 'irule' in job.command: if policyId is not None: if job.comment.startswith(policyId): jobList.append(job) else: jobList.append(job) for job in jobList: logger.info('removing the job ' + job.comment) # remove the job cron.remove(job) # commit the change to the cron scheduler cron.write_to_user(user=True) logger.info('Policies removed')
def cron_thyself(original_arguments=[]): # Get the current time now = datetime.datetime.now() path, filename = get_script_path_and_name() from crontab import CronTab logging.info('Cron scheduling %s to happen in 24 hours (minute: %d hour: %d)' % (filename, now.minute, now.hour)) cron = CronTab(user=True) jobs = cron.find_command(filename) jobs = [job for job in jobs] logging.debug('Existing cron jobs are: %s' % jobs) # If no job already exists, create one if not jobs: command = os.path.join(path, filename) + ' ' + ' '.join(original_arguments[1:]) logging.info("No existing job detected. Creating a new one") job = cron.new(command, "Automatically log into hotspot every 24 hours.") # If we create a new job for this exact minute, then the job will run immediately after we create it. # Instead create the job for the past minute. minute = now.minute - 1 else: if len(jobs) > 1: logging.warn("More than 1 cron lines for %s. Using the first one." % filename) job = jobs[0] minute = now.minute job.minute.on(minute) job.hour.on(now.hour) logging.info('Writing Cron job: %s' % job) cron.write()
def shed_rm(request,shed_id): shed = Shed.objects.get(id=shed_id) tab = CronTab(user=settings.CRONTAB_USER) tab.remove_all(comment=shed.job.name) tab.write() shed.delete() return redirect ('/mailer/viewshed/')
def cronHandler(data): if not data: return s = data.split(':') cronCommand = s[1].strip() if cronCommand not in ["on", "off"]: print("Cron command invalid, should be 'on' or 'off'. Command: %s" % cronCommand) return cronString = s[2].strip() if not CronSlices.is_valid(cronString): print("Cron time string invalid. Time string: %s" % cronString) return # Now we've validated the command, set a cron job cron_file = CronTab(user=True) it = cron_file.find_command(cronCommand) try: job = it.next() print("Found existing cron task for %s" % cronCommand) except StopIteration: job = cron_file.new(command="echo %s >> /tmp/test.txt" % cronCommand) print("Creating new cron task for %s" % cronCommand) job.setall(cronString) job.enable() cron_file.write()
class CronTabs(list): """Singleton dictionary of all detectable crontabs""" _all = None _self = None def __new__(cls, *args, **kw): if not cls._self: cls._self = super(CronTabs, cls).__new__(cls, *args, **kw) return cls._self def __init__(self): if not self: for loc in KNOWN_LOCATIONS: self.add(*loc) def add(self, cls, *args): for tab in cls(*args, tabs=self): self.append(tab) self._all = None @property def all(self): """Return a CronTab object with all jobs (read-only)""" if self._all is None: self._all = CronTab(user=False) for tab in self: for job in tab: if job.user is None: job.user = tab.user or 'unknown' self._all.append(job) return self._all
def parse(file_name, aws_id, aws_secret): """ Create a job in user's cron file for every machine schedule specified in json map """ machines = json.loads(open(file_name).read()) cron = CronTab(user=True) for machine in machines: # Don't create a line in cron if it already exists! for op in ['start', 'stop']: # Times defined in machine should be "start_time" or "stop_time" op_time = datetime.strptime(machine[op + '_time'], '%H:%M') # The op should conform to the options this program takes: start / stop job = cron.new( command='python {path} {op} {name} --id {aws_id} --secret {aws_secret} --region {region}'.format( path=os.path.realpath(__file__), op=op, name=machine['name'], aws_id=aws_id, aws_secret=aws_secret, region=machine['region'] ) ) job.hour.on(op_time.hour) job.minute.on(op_time.minute) cron.write()
def _add_cron_tab(self, scheduled_time, object_id): LOG.debug(_("Add new cron tab at: %s") % scheduled_time ) cron = CronTab() python_exec = (subprocess.check_output(['which','python'])).rstrip('\n') cwd = os.path.dirname(__file__) scheduler_path = cwd + "/timing-scheduler/run_scheduled_instance.py" config_file_path = self._get_config_file_path() config_file_params = " --config-file /etc/nova/nova.conf" if config_file_path: config_file_params = '--config-file ' + config_file_path LOG.debug(_("Config file params %s") % config_file_params ) object_id_params = "--object_id %s" % object_id cmd = python_exec + " "+ \ scheduler_path + " " + \ config_file_params + " " + \ object_id_params LOG.debug(_("Cron job cmd %s") % cmd ) job = cron.new(command=cmd) job.hour.on(scheduled_time.hour) job.minute.on(scheduled_time.minute) job.day.on(scheduled_time.day) job.month.on(scheduled_time.month) cron.write()
def cronjob(): cron = CronTab() api_request = 'curl http://127.0.0.1:5000/api/reminder' job = cron.new(command = api_request, comment = "Reminding all users of jobs to be completed today.") job.setall('0 0 * * *') job.run()
def unsetschedule(request): if not is_admin(request): return HTTPForbidden() cron_name = request.matchdict['name'] cron = CronTab(user=True) cron.remove_all(comment=cron_name) cron.write() return []
def check_cron(): # Check if cron exists if not add one # Writing job not working for unknown reason cron = CronTab(user="******") if cron.find_command(cron_command): return else: print "add '0 * * * * bash /etc/madari/hourly.sh' to crontab for root"
def setup_crontab(): job_command = 'sudo service nginx stop && /opt/certbot-auto renew && sudo service nginx start' user_crontab = CronTab(user=True) if job_command not in str(user_crontab): job = user_crontab.new(command=job_command, comment="Renew lets-encrypt every month") job.every().month() job.enable() user_crontab.write()
def setUp(self): self.crontab = CronTab(tab="")
def test_04_zero_seq(self): tab = CronTab(tab=""" */0 * * * * command """) self.assertEqual(len(tab), 0)
def get_all_jobs(): cron = CronTab(user=True) list = [] for job in cron: list.append(job) return list
curator_settings[operation].setdefault( unit, {}).setdefault(value, []).append(project) else: if unit.lower() == "hours": logger.error( 'time unit "hours" is currently not supported due to our current index level granularity is in days' ) else: logger.error('an unknown time unit of ' + unit + ' was provided... Record skipped') else: logger.error('an unsupported or unknown operation ' + operation + ' was provided... Record skipped') my_cron = CronTab() default_job = my_cron.new(command=default_command, comment='Default generated job for curator') default_job.every().day() for operation in curator_settings: for unit in curator_settings[operation]: for value in curator_settings[operation][unit]: base_cmd = '/usr/bin/curator --loglevel ERROR ' + connection_info + ' ' + operation + ' indices --timestring %Y.%m.%d' tab_command = base_cmd + ' --older-than ' + str( value) + ' --time-unit ' + unit for project in curator_settings[operation][unit][value]: tab_command = tab_command + ' --prefix ' + project + '.'
# DOCUMENTATION: ''' Source: https://stackabuse.com/scheduling-jobs-with-python-crontab/ ''' # Import Library from crontab import CronTab # Access Class Object cron = CronTab() # Create Function script = 'test_crontab.py' # Create A New Job job = cron.new(command=script) job.minute.every(1) job.enable()
def set_reminder(data): print(data.set_reminder) cron = CronTab(user=True) job = cron.new(command='/usr/bin/env python3 test.py') job.minute.every(1) cron.write()
from crontab import CronTab cron = CronTab(user='******') job = cron.new(command='python3 /home/syntizen/RAMU/workspace/email/sample.py') job.minute.every(1) cron.write()
def limpiar_cron_job(actividad): cron = CronTab(user=True) cm = f"{PY} {settings.BASE_DIR}/manage.py closeactivity {actividad.pk} > /tmp/cronlog.txt 2>&1" cron.remove_all(command=cm) cron.write()
#!/usr/bin/env python3 import datetime from crontab import CronTab import os.path file = open('test.txt', 'a') file.write('\nAccessed on ' + str(datetime.datetime.now())) file.close cron = CronTab(user=True) for job in cron: print job
from crontab import CronTab cron = CronTab(user=True) job = cron.new(command='python3 main.py') job.minute.every(1) cron.write()
from model.sentiment import * from stream import * from autoStream import * from utility import * from config import * # set Flask app = Flask(__name__) # set CNN model global graph graph = tf.get_default_graph() vocab, tokenizer, max_length, model = load_variabels() # Set crontab cron = CronTab(user=curr_username) cron.remove_all() cron.write() #-------------------- ROUTE View --------------------------------------------------- """ Route View berhubungan dengan untuk menampilkan templates """ # index route """ index untuk view yang baru - menampilkan current_file - status current_file apakah sudah diprediksi atau belum - tombol prediksi - tombol download """
} print(var.get(min(var))) print("") if (var.get(min(var))) == 'A': print("Optimaler Startzeitpunkt ist:") print( datetime.datetime.fromtimestamp(int(start) / 1000).strftime('%d.%m.%Y %H:%M')) print("mit dem Durchschnitspreis von:") print(min(var)) from crontab import CronTab cron = CronTab(user='******') cron.remove_all(comment='last3') cron.remove_all(comment='last3e') job = cron.new(command='/home/pi/Python/19E.sh', comment='last3') job.hour.on(h) job.minute.on(15) cron.write() job1 = cron.new(command='/home/pi/Python/19D.sh', comment='last3e') job1.hour.on(h9) job1.minute.on(1) cron.write() elif (var.get(min(var))) == 'B': print("Optimaler Startzeitpunkt ist:")
# elif int(cmd) == 8: # Migrate to a target process, currently WINDOWS ONLY **PLACEHOLDER** TODO IMPLEMENT THIS # targetPid = s.recv(BUFF_SIZE).decode() # Target PID to migrate to elif int(cmd ) == 8: # Persistence, registry for Windows, Crontab for *nix if family == 'Windows': # Do Windows persistence since we're on Windows exe = 'python ' + cwd + '\\' + sys.argv[0] + ' ' + sys.argv[ 1] + ' ' + sys.argv[2] key = OpenKey( HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Run", 0, KEY_ALL_ACCESS) # Create our Run reg key entry using this script and our arguments SetValueEx(key, 'client', 0, REG_SZ, exe) key.Close() else: # We're on a *nix system, try Cron exe = 'python ' + cwd + '/' + sys.argv[0] + ' ' + sys.argv[ 1] + ' ' + sys.argv[2] cron = CronTab(user=user) reboot = '@reboot ' + exe # Make our script run on reboot job = cron.new(command=exe) cron.write() s.send('Success'.encode()) elif int(cmd) == 0: # Exit exit() else: # Not really distinct from if cmd == 0, but covers invalid command args. just exit exit()
def next(self): return math.ceil(CronTab.next(self)) * 1000
def __init__(self, crontab, callback): CronTab.__init__(self, crontab) PeriodicCallback.__init__(self, callback, self.next(), IOLoop.current())
import os from crontab import CronTab from dotenv import load_dotenv import sys import requests my_cron = CronTab(True) dotenv_path = os.path.dirname(os.path.dirname( os.path.abspath(__file__))) + '/DjangoRestApi/.env' load_dotenv(dotenv_path) API_ENDPOINT = os.getenv('API_ENDPOINT') WEB_CLIENT = os.getenv('WEB_CLIENT') CLIENT_ID = os.getenv('CLIENT_ID') CLIENT_SECRET = os.getenv('CLIENT_SECRET') DOMAIN_API = os.environ.get('API_ENDPOINT') username = sys.argv[1] password = sys.argv[2] data = { 'username': username, 'password': password, } r = requests.post(API_ENDPOINT + '/v1/auth/login-admin', data=data) data = r.json() token = data['data']['access_token'] bearer = data['data']['token_type'] headers = {
from crontab import CronTab PATH_TO_SYSTEM_TAB_FILE = "data.tab" cron_obj = CronTab(tabfile=PATH_TO_SYSTEM_TAB_FILE) job_first = cron_obj.new(command="python3 path/to/rest/api/server.py") job_first.hour.every(6) job_second = cron_obj.new(command="python3 path/to/rest/api/client.py") job_second.every(3).hours() for job in cron_obj: print(job) cron_obj.write()
import mock try: from StringIO import StringIO except ImportError: from io import StringIO from django.core.management import call_command from django.test import TestCase from django.core.management.base import CommandError from crontab import CronTab from kronos.settings import KRONOS_BREADCRUMB from kronos import registry, load crontab = CronTab('') def get_crontab(*args, **kwargs): return crontab class TestCase(TestCase): def setUp(self): load() crontab.remove_all() # @patch('subprocess.Popen') # def test_unintalltasks(self, mock): # """Test uninstalling tasks with the ``uninstalltasks`` command.""" # mock.return_value = Mock(
def setUp(self): self.crontab = CronTab(tab=INITIAL_TAB)
xfce4panel_process.kill() time.sleep(5) log.info("Start xfce4-panel again.") log.info("xfce4-panel started with exit code: " + str(subprocess.call("xfce4-panel", shell=True))) elif args.mode == "schedule": DEFAULT_CRON = "0 * * * *" # every hour from crontab import CronTab, CronSlices cron_schedule = DEFAULT_CRON script_file_path = os.path.realpath(__file__) command = sys.executable + " '" + script_file_path + "' check> /proc/1/fd/1 2>/proc/1/fd/2" cron = CronTab(user=True) # remove all other tasks cron.remove_all(command=command) job = cron.new(command=command) if CronSlices.is_valid(cron_schedule): log.info("Scheduling cron check xfdesktop task with with cron: " + cron_schedule) job.setall(cron_schedule) job.enable() cron.write() else: log.info("Failed to schedule check xfdesktop. Cron is not valid.") log.info("Running cron jobs:") for job in cron:
""" Collecting Deployments configured for Scaling """ import os import pathlib import json import logging import shutil import pykube import re import urllib.request import boto3 import time from datetime import datetime from crontab import CronTab EXECUTION_TIME = 'datetime.datetime.now().strftime("%d-%m-%Y %H:%M UTC")' crontab_instance = CronTab(user="******") def create_job_directory(): """ This directory will hold the temp python scripts to execute the scaling jobs """ temp__dir = '/tmp/scaling_jobs' if os.path.isdir(temp__dir): shutil.rmtree(temp__dir) pathlib.Path(temp__dir).mkdir(parents=True, exist_ok=True) def clear_cron(): """ This is needed so that if any one removes his scaling action it should not be trigger again """ crontab_instance.remove_all(comment="Scheduling_Jobs")
class EnvTestCase(unittest.TestCase): """Test vixie cron user addition.""" def setUp(self): self.crontab = CronTab(tab=INITIAL_TAB) def test_01_consistancy(self): """Read in crontab and write out the same""" self.assertEqual(INITIAL_TAB, str(self.crontab)) def test_02_top_vars(self): """Whole file env variables""" crontab = CronTab(tab="SHELL=dash\n") self.assertEqual(str(crontab), "SHELL=dash\n") self.assertEqual(crontab.env['SHELL'], 'dash') crontab.env['SHELL'] = 'bash' self.assertEqual(str(crontab), "SHELL=bash\n") self.assertEqual(crontab.env['SHELL'], 'bash') def test_03_get_job_var(self): """Test each of the job env structures""" for job, expected in zip(self.crontab, [ { 'PERSONAL_VAR': 'bar', 'CRON_VAR': 'fork' }, { 'PERSONAL_VAR': 'bar', 'CRON_VAR': 'spoon' }, { 'PERSONAL_VAR': 'bar', 'CRON_VAR': 'knife' }, { 'PERSONAL_VAR': 'bar', 'CRON_VAR': 'knife', 'SECONDARY': 'fork' }, ]): self.assertEqual(OrderedDict(job.env.all()), expected) def test_04_set_job_var(self): """Test that variables set are applied correctly""" self.crontab[1].env['CRON_VAR'] = 'javlin' self.assertEqual(self.crontab[1].env.all(), { 'PERSONAL_VAR': 'bar', 'CRON_VAR': 'javlin' }) self.crontab[2].env['CRON_VAR'] = 'javlin' self.assertEqual(self.crontab[2].env.all(), { 'PERSONAL_VAR': 'bar', 'CRON_VAR': 'javlin' }) self.assertEqual(self.crontab[3].env['PERSONAL_VAR'], 'bar') self.assertEqual(self.crontab[3].env.all(), { 'PERSONAL_VAR': 'bar', 'CRON_VAR': 'javlin', 'SECONDARY': 'fork' }) self.crontab.env['PERSONAL_VAR'] = 'foo' self.assertEqual(self.crontab[2].env.all(), { 'PERSONAL_VAR': 'foo', 'CRON_VAR': 'javlin' }) self.crontab.env['CRON_VAR'] = 'fork' self.assertEqual(self.crontab[0].env.all(), { 'PERSONAL_VAR': 'foo', 'CRON_VAR': 'fork' }) self.assertEqual( str(self.crontab), """PERSONAL_VAR=foo CRON_VAR=fork 34 12 * * * eat_soup CRON_VAR=javlin 35 12 * * * eat_salad 36 12 * * * eat_icecream SECONDARY=fork 38 12 * * * eat_steak """) def test_05_no_env(self): """Test that we get an error asking for no var""" with self.assertRaises(KeyError): self.crontab.env['BLUE_BOTTLE'] with self.assertRaises(KeyError): self.crontab[0].env['RED_BOTTLE'] def test_06_env_access(self): cron = CronTab(tab=""" MYNAME='Random' * * * * * echo "first: $MYNAME" * * * * * echo "second: $MYNAME" * * * * * echo "third: $MYNAME" """) for job in cron: self.assertEqual(job.env['MYNAME'], "Random") def test_07_mutated_dict(self): """Test when the ordered dict is changed during loop""" cron = CronTab(tab=""" ALL='all' ABCD='first' * * * * * echo "first" """) def test_08_space_quotes(self): """Test that spaces and quotes are handled correctly""" cron = CronTab(tab=""" A= 123 B=" 123 " C=' 123 ' D= " 123 " E= 1 2 3 """) self.assertEqual(cron.env['A'], '123') self.assertEqual(cron.env['B'], ' 123 ') self.assertEqual(cron.env['C'], ' 123 ') self.assertEqual(cron.env['D'], ' 123 ') self.assertEqual(cron.env['E'], '1 2 3') self.assertEqual( str(cron), """A=123 B=" 123 " C=" 123 " D=" 123 " E="1 2 3" """) def test_09_delete_middle(self): """Test that a delete doesn't remove vars""" self.crontab.remove_all(command='eat_icecream') self.crontab.remove_all(command='eat_soup') self.assertEqual( str(self.crontab), """PERSONAL_VAR=bar CRON_VAR=spoon 35 12 * * * eat_salad CRON_VAR=knife SECONDARY=fork 38 12 * * * eat_steak """)
from crontab import CronTab if __name__ == '__main__': #tab = CronTab(user='******',fake_tab='True') tab = CronTab('yangxu') cmd = 'python test.py' #cron_job = tab.new(command = cmd, comment='main command') cron_job = tab.new(command=cmd) cron_job.minutes.every(1) cron_job.enable() print 'done' #cron_job.hour.every(3) #tab.write() #print tab.render()
from crontab import CronTab cron = CronTab(tabfile='filename.tab') job = cron.new(command='echo "123"') job.minute.every(1) cron.write()
from crontab import CronTab cron = CronTab(user='******') job = cron.new(command='python3 process.py') job.minute.every(10) cron.write()
import sys, os sys.path.append("./") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") import django django.setup() from opencsp.models import Server from crontab import CronTab cron = CronTab(user=True) cron.remove_all(comment='checkserver') scripts_path = os.path.dirname(os.path.abspath(__file__)) for server in Server.objects.filter(server_active=True): command = os.path.join(scripts_path, 'check_for_new.py {0}'.format(server.pk)) #print 'Install', command job = cron.new(command=command, comment='checkserver') job.setall('* * * * *') job.enable(True) cron.write() #print cron.render()
class EveryTestCase(unittest.TestCase): """Test basic functionality of crontab.""" def setUp(self): self.crontab = CronTab( tabfile=os.path.join(TEST_DIR, 'data', 'test.tab')) def test_00_minutes(self): """Every Minutes""" for job in self.crontab: job.every(3).minutes() self.assertEqual(job.slices.clean_render(), '*/3 * * * *') job.minutes.every(5) self.assertEqual(job.slices.clean_render(), '*/5 * * * *') def test_01_hours(self): """Every Hours""" for job in self.crontab: job.every(3).hours() self.assertEqual(job.slices.clean_render(), '0 */3 * * *') def test_02_dom(self): """Every Day of the Month""" for job in self.crontab: job.every(3).dom() self.assertEqual(job.slices.clean_render(), '0 0 */3 * *') def test_03_single(self): """Every Single Hour""" for job in self.crontab: job.every().hour() self.assertEqual(job.slices.clean_render(), '0 * * * *') def test_04_month(self): """Every Month""" for job in self.crontab: job.every(3).months() self.assertEqual(job.slices.clean_render(), '0 0 1 */3 *') def test_05_dow(self): """Every Day of the Week""" for job in self.crontab: job.every(3).dow() self.assertEqual(job.slices.clean_render(), '0 0 * * */3') def test_06_year(self): """Every Year""" for job in self.crontab: job.every().year() self.assertEqual(job.slices.render(), '@yearly') self.assertEqual(job.slices.clean_render(), '0 0 1 1 *') self.assertRaises(ValueError, job.every(2).year) def test_07_reboot(self): """Every Reboot""" for job in self.crontab: job.every_reboot() self.assertEqual(job.slices.render(), '@reboot') self.assertEqual(job.slices.clean_render(), '* * * * *') def test_08_newitem(self): """Every on New Item""" job = self.crontab.new(command='hourly') job.every().hour() self.assertEqual(job.slices.render(), '@hourly') job = self.crontab.new(command='firstly') job.hours.every(2) self.assertEqual(job.slices.render(), '* */2 * * *')
def setUp(self): self.crontab = CronTab( tabfile=os.path.join(TEST_DIR, 'data', 'test.tab'))
def test_crontab(self) -> None: self.assertEqual( CronTab("@daily").matchers, self.periodic.crontab.matchers)
# import os from crontab import CronTab # # Setup the cron command to run from the current user's omniEngine directory. # homeDir = os.environ['HOME'] engineCommand = 'python {0}/omniEngine/omniEngine.py >> {1}/omniEngine/logs/omniEngine.log'.format( homeDir, homeDir) engineComment = 'Update OmniEngne DB using RPC' # # Access the current users' CronTab # cron = CronTab(user=True) # Look for existing job found = cron.find_command('omniEngine.py') job = next(found, None) if job is not None: # If existing job, clear all fields and set correct values print "Found existing job: " print job job.clear() job.set_command(engineCommand) job.set_comment(engineComment) else: # If no existing job, set up job from scratch print "Adding job." job = cron.new(command=engineCommand, comment='load Tx into DB using RPC')