Python crontab.CronTab() Examples
The following are 22
code examples of crontab.CronTab().
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
crontab
, or try the search function
.
Example #1
Source File: croni.py From daily-wallpaper with MIT License | 6 votes |
def __init__(self): self.cron = CronTab(user=True) params = PARAMS % os.getuid() filename = os.path.join(os.path.expanduser('~'), FILE) desktop_environment = get_desktop_environment() if desktop_environment == 'gnome' or \ desktop_environment == 'unity' or \ desktop_environment == 'budgie-desktop': gset = GSET_GNOME % filename elif desktop_environment == "mate": gset = GSET_MATE % filename elif desktop_environment == "cinnamon": gset = GSET_CINNAMON % filename else: gset = None if gset is not None: self.command = 'sleep 20;{0};{1} {2} {4} && {3} {4}'.format( params, EXEC, SCRIPT, gset, NO_OUTPUT) else: self.command = None
Example #2
Source File: __init__.py From paperboy with Apache License 2.0 | 6 votes |
def schedule_cron(command, interval, crontab=None): from crontab import CronTab, CronItem if not os.path.exists(crontab): with open(crontab, 'w'): pass if crontab: c = CronTab(tabfile=crontab) else: c = CronTab(user=getpass.getuser()) job = CronItem.from_line(interval + ' ' + command, cron=c) c.append(job) c.write() return c, job
Example #3
Source File: fetch.py From munin-influxdb with BSD 2-Clause "Simplified" License | 6 votes |
def uninstall_cron(): if os.geteuid() != 0: print("It seems you are not root, please run \"muninflux fetch --uninstall-cron\" again with root privileges".format(sys.argv[0])) sys.exit(1) try: import crontab except ImportError: from vendor import crontab cron = crontab.CronTab(user=CRON_USER) jobs = list(cron.find_comment(CRON_COMMENT)) cron.remove(*jobs) cron.write() return len(jobs)
Example #4
Source File: fetch.py From munin-influxdb with BSD 2-Clause "Simplified" License | 6 votes |
def install_cron(script_file, period): if os.geteuid() != 0: print("It seems you are not root, please run \"muninflux fetch --install-cron\" again with root privileges".format(sys.argv[0])) sys.exit(1) try: import crontab except ImportError: from vendor import crontab cron = crontab.CronTab(user=CRON_USER) job = cron.new(command=script_file, user=CRON_USER, comment=CRON_COMMENT) job.minute.every(period) if job.is_valid() and job.is_enabled(): cron.write() return job.is_valid() and job.is_enabled()
Example #5
Source File: models.py From fresh_script with MIT License | 6 votes |
def setupCron(self): cron = CronTab() cron_setting = textwrap.dedent("""\ ┌───────────── minute (0 - 59) │ ┌───────────── hour (0 - 23) │ │ ┌───────────── day of month (1 - 31) │ │ │ ┌───────────── month (1 - 12) │ │ │ │ ┌───────────── day of week (0 - 6) (Sunday to Saturday; │ │ │ │ │ 7 is also Sunday on some systems) │ │ │ │ │ │ │ │ │ │ * * * * * command to execute """) choice = input(cron_setting) # Reddit class
Example #6
Source File: setup.py From SSHMonitor2.7 with GNU General Public License v3.0 | 6 votes |
def cron_tab(self): #Count need to be 1 in order to write to the crontab. #Basically, checking for grep being None or not None will #not work in this case and we need to check for 2 occurances. count=0 cmd="/bin/bash /home/root/.ssh/is_sshm_running.sh" cron = CronTab(user='root') job = cron.new(command=cmd) job.minute.every(1) for job in cron: grep = re.search(r'\/is_sshm_running.sh', str(job)) if grep is not None: count+=1 #if count < 2 and self.install: if count < 2: Logger.log("INFO", "Installing crontab.") cron.write() Logger.log("WARN","Please nesure that the crontab was actually installed!") Logger.log("WARN","To do so please run(without quotes) => 'sudo crontab -l -u root'")
Example #7
Source File: coursera_offline.py From coursera-offline with GNU General Public License v3.0 | 6 votes |
def schedule_synch(day, email, password): if not day: exit_with_message('Failed to schedule synch: Invalid day') if not email or not password: exit_with_message('Invalid username and password') day = day.upper() if not day in ['MON','TUE','WED','THU','FRI','SAT','SUN']: exit_with_message('Failed to schedule synch: Invalid day') user_cron = CronTab(user=True) cmd = "%s -d %s -S -e %s -p %s" % (os.path.abspath(__file__), COURSE_DIR, email, password) job = user_cron.new(command=cmd) job.hour.on(11) job.minute.on(59) job.dow.on(day) user_cron.write() print 'Cron Job added'
Example #8
Source File: crons.py From dgenies with GNU General Public License v3.0 | 5 votes |
def __init__(self, base_dir, debug): """ :param base_dir: software base directory path :type base_dir: str :param debug: True to enable debug mode :type debug: bool """ self.base_dir = base_dir self.debug = debug self.my_cron = CronTab(user=getpass.getuser()) self.config = AppConfigReader() self.local_scheduler_pid_file = os.path.join(self.config.config_dir, ".local_scheduler_pid")
Example #9
Source File: common.py From docker-mkdocs with MIT License | 5 votes |
def _set_auto_update(interval): """ Creates cron job for auto updating repository :param interval: (every x minutes) :return: """ os.system(f'crond') cron = CronTab(user='root') cron.remove_all() job = cron.new(command='bootstrap update', comment='update') job.minute.every(interval) cron.write()
Example #10
Source File: __init__.py From paperboy with Apache License 2.0 | 5 votes |
def unschedule_cron(command, crontab=None): from crontab import CronTab if crontab: c = CronTab(tabfile=crontab) else: c = CronTab(user=getpass.getuser()) for line in c.lines: if str(line) == command: line.delete() c.write() return True return False
Example #11
Source File: schedule.py From paperboy with Apache License 2.0 | 5 votes |
def schedule(self, job, reports, job_dir, interval): from crontab import CronTab, CronItem # must occur in gunicorn process if self.runner is None: self.runner = threading.Thread(target=run_tasks, args=(self.add_queue, self.delete_queue)) self.runner.daemon = True self.runner.start() c = CronTab(user=getpass.getuser()) cjob = CronItem.from_line(interval + ' echo test', cron=c) self.tasks[job.id] = (job, reports, job_dir, interval, cjob) logging.critical('Scheduling job: %s' % str(job.id)) self.add_queue.put((job, reports, job_dir, interval, cjob))
Example #12
Source File: install.py From detect-secrets-server with Apache License 2.0 | 5 votes |
def _install_cron(args): # Get user's current crontab, so as not to override it old_content = [] cron = CronTab(user=True) with tempfile.NamedTemporaryFile() as temp: cron.write(temp.name) # Ignore all previous entries for line in temp.readlines(): line = line.decode() if line and 'detect-secrets-server' not in line: old_content.append(line.strip()) # Create jobs from tracked repositories jobs = [] for repo, is_local in list_tracked_repositories(args): command = '{} detect-secrets-server scan {}'.format( repo['crontab'], repo['repo'] ) if is_local: command += ' --local' if args.root_dir: command += ' --root-dir {}'.format(args.root_dir) if args.output_hook_command: command += ' {}'.format(args.output_hook_command) jobs.append(command.strip()) # Construct new crontab content = '\n'.join(jobs) if old_content: content = '{}\n\n{}'.format( '\n'.join(old_content), content, ) cron = CronTab( tab=content, user=True, ) cron.write_to_user(user=True)
Example #13
Source File: cron_scheduler.py From dagster with Apache License 2.0 | 5 votes |
def get_cron_tab(self): return CronTab(user=True)
Example #14
Source File: init_settings.py From WatchAD with GNU General Public License v3.0 | 5 votes |
def set_crontab_tasks(): """ 设置定时任务: 1. 定期删除过期的ES索引 2. 定时扫描万能钥匙 """ logger.info("set crontab tasks.") my_user_cron = CronTab(user=True) # 定时扫描万能钥匙 每2分钟一次 skeleton_job = my_user_cron.new( command='/usr/bin/python3 {project_dir}/scripts/skeleton_key_scan.py >/dev/null 2>&1' .format(project_dir=project_dir)) skeleton_job.minute.every(2) skeleton_job.set_comment("skeleton_job") logger.info("set skeleton_key_scan every 2 min.") # my_user_cron.remove(skeleton_job) # 定时删除过期索引 每天删除 delete_index_job = my_user_cron.new( command='/usr/bin/python3 {project_dir}/scripts/delete_index.py >/dev/null 2>&1' .format(project_dir=project_dir)) delete_index_job.day.every(1) delete_index_job.hour.on(0) delete_index_job.minute.on(0) delete_index_job.set_comment("delete_index_job") logger.info("set delete_index_job every day.") # my_user_cron.remove(delete_index_job) my_user_cron.write()
Example #15
Source File: crontab_schedule.py From coal-mine with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): super(FastCronTab, self).__init__(*args, **kwargs) # Degenerate case where CronTab is much too slow self.every_minute = args[0] == '* * * * *' self.cached_now = None self.cached_next = None
Example #16
Source File: install_cron.py From janeway with GNU Affero General Public License v3.0 | 5 votes |
def handle(self, *args, **options): """Installs Cron :param args: None :param options: None :return: None """ action = options.get('action') tab = CronTab(user=True) virtualenv = os.environ.get('VIRTUAL_ENV', None) jobs = [ {'name': 'janeway_cron_job', 'time': 30, 'task': 'execute_cron_tasks'}, {'name': 'janeway_ithenticate_job', 'time': 30, 'task': 'store_ithenticate_scores'}, ] if settings.ENABLE_ENHANCED_MAILGUN_FEATURES: jobs.append({'name': 'janeway_mailgun_job', 'time': 60, 'task': 'check_mailgun_stat'}) for job in jobs: current_job = find_job(tab, job['name']) if not current_job: django_command = "{0}/manage.py {1}".format(settings.BASE_DIR, job['task']) if virtualenv: command = '%s/bin/python3 %s' % (virtualenv, django_command) else: command = '%s' % (django_command) cron_job = tab.new(command, comment=job['name']) cron_job.minute.every(job['time']) else: print("{name} cron job already exists.".format(name=job['name'])) if action == 'test': print(tab.render()) elif action == 'quiet': pass else: tab.write()
Example #17
Source File: schedule_scaling.py From kube-schedule-scaler with GNU General Public License v3.0 | 5 votes |
def clear_cron(): """ This is needed so that if any one removes his scaling action it should not be trigger again """ my_cron = CronTab(user='root') my_cron.remove_all(comment="Scheduling_Jobs") my_cron.write()
Example #18
Source File: cron.py From platform with GNU General Public License v3.0 | 5 votes |
def __init__(self, platform_config): self.platform_config = platform_config self.cron = CronTab(user=self.platform_config.cron_user()) self.log = logger.get_logger('cron')
Example #19
Source File: Scrummage.py From Scrummage with GNU General Public License v3.0 | 4 votes |
def api_tasks_delete(taskid): try: if 'Authorization' in request.headers: Auth_Token = request.headers['Authorization'].replace("Bearer ", "").replace("bearer ", "") Authentication_Verified = API_verification(Auth_Token) if Authentication_Verified["Token"]: if Authentication_Verified["Admin"]: if request.method == 'POST': del_id = int(taskid) Cursor.execute("SELECT frequency FROM tasks WHERE task_id = %s", (del_id,)) result = Cursor.fetchone() if result: Cron_Command = f'/usr/bin/python3 {File_Path}/plugin_caller.py -t {str(del_id)}' try: my_cron = CronTab(user=getpass.getuser()) for job in my_cron: if job.command == Cron_Command: my_cron.remove(job) my_cron.write() except: return jsonify({"Error": f"Failed to remove old cronjob. No changes made to task.", "Attempted Cronjob": Cron_Command}), 500 Cursor.execute("DELETE FROM tasks WHERE task_id = %s;", (del_id,)) Connection.commit() User = Authentication_Verified["Username"] Message = f"Task ID {str(del_id)} deleted by {User}." app.logger.warning(Message) Create_Event(Message) return jsonify({"Message": f"Successfully deleted task id {str(del_id)}."}), 200 else: return jsonify({"Error": "Method not allowed."}), 500 else: return jsonify({"Error": "Insufficient privileges."}), 500 else: if Authentication_Verified["Message"]: return jsonify({"Error": Authentication_Verified["Message"]}), 500 else: return jsonify({"Error": "Unauthorised."}), 500 else: return jsonify({"Error": "Missing Authorization header."}), 500 except Exception as e: app.logger.error(e) return jsonify({"Error": "Unknown error."}), 500
Example #20
Source File: Scrummage.py From Scrummage with GNU General Public License v3.0 | 4 votes |
def duplicate_task(taskid): try: if session.get('user') and session.get('is_admin'): def dup_task(dup_id): dup_id = int(dup_id) Cursor.execute("SELECT * FROM tasks WHERE task_id = %s", (dup_id,)) result = Cursor.fetchone() if result: Current_Timestamp = General.Date() # Variable set to create consistency in timestamps across two seperate database queries. Cursor.execute('INSERT INTO tasks (query, plugin, description, frequency, task_limit, status, created_at, updated_at) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)', (result[1], result[2], result[3], result[4], str(result[5]), "Stopped", str(Current_Timestamp), str(Current_Timestamp))) Connection.commit() if result[4]: time.sleep(1) Cursor.execute("SELECT * FROM tasks WHERE query = %s AND plugin = %s AND description = %s AND frequency = %s AND task_limit = %s AND status = %s AND created_at = %s AND updated_at = %s;", (result[1], result[2], result[3], result[4], str(result[5]), "Stopped", str(Current_Timestamp), str(Current_Timestamp),)) result = Cursor.fetchone() task_id = result[0] try: my_cron = CronTab(user=getpass.getuser()) job = my_cron.new(command=f'/usr/bin/python3 {File_Path}/plugin_caller.py -t {str(task_id)}') job.setall(result[4]) my_cron.write() except Exception as e: app.logger.error(e) Message = f"Task ID {str(dup_id)} duplicated by {session.get('user')}." app.logger.warning(Message) Create_Event(Message) if "," in taskid: for task in taskid.split(","): dup_task(task) else: dup_task(taskid) return redirect(url_for('tasks')) else: if not session.get('user'): session["next_page"] = "tasks" return redirect(url_for('no_session')) else: return redirect(url_for('tasks')) except Exception as e: app.logger.error(e) return redirect(url_for('tasks'))
Example #21
Source File: schedule_scaling.py From kube-schedule-scaler with GNU General Public License v3.0 | 4 votes |
def stack_job_creator(): """ Create CronJobs for configured Stacks """ stacks__to_scale = stacks_to_scale() print("Stacks collected for scaling: ") for stacks, schedules in stacks__to_scale.items(): stack = stacks.split("/")[1] namespace = stacks.split("/")[0] for n in range(len(schedules)): schedules_n = schedules[n] replicas = schedules_n.get('replicas', None) minReplicas = schedules_n.get('minReplicas', None) maxReplicas = schedules_n.get('maxReplicas', None) schedule = schedules_n.get('schedule', None) print("Stack: %s, Namespace: %s, Replicas: %s, MinReplicas: %s, MaxReplicas: %s, minSchedule: %s" % (stack, namespace, replicas, minReplicas, maxReplicas, schedule)) with open("/root/schedule_scaling/templates/stack-script.py", 'r') as script: script = script.read() stack_script = script % { 'namespace': namespace, 'name': stack, 'replicas': replicas, 'minReplicas': minReplicas, 'maxReplicas': maxReplicas, 'time': EXECUTION_TIME, } i = 0 while os.path.exists("/tmp/scaling_jobs/%s-%d.py" % (stack, i)): i += 1 script_creator = open("/tmp/scaling_jobs/%s-%d.py" % (stack, i), "w") script_creator.write(stack_script) script_creator.close() cmd = ['sleep 50 ; . /root/.profile ; /usr/bin/python', script_creator.name, '2>&1 | tee -a /tmp/scale_activities.log'] cmd = ' '.join(map(str, cmd)) scaling_cron = CronTab(user='root') job = scaling_cron.new(command=cmd) try: job.setall(schedule) job.set_comment("Scheduling_Jobs") scaling_cron.write() except Exception: print('Stack: %s has syntax error in the schedule' % (stack)) pass
Example #22
Source File: schedule_scaling.py From kube-schedule-scaler with GNU General Public License v3.0 | 4 votes |
def deploy_job_creator(): """ Create CronJobs for configured Deployments """ deployments__to_scale = deployments_to_scale() print("Deployments collected for scaling: ") for deploy, schedules in deployments__to_scale.items(): deployment = deploy.split("/")[1] namespace = deploy.split("/")[0] for n in range(len(schedules)): schedules_n = schedules[n] replicas = schedules_n.get('replicas', None) minReplicas = schedules_n.get('minReplicas', None) maxReplicas = schedules_n.get('maxReplicas', None) schedule = schedules_n.get('schedule', None) print("Deployment: %s, Namespace: %s, Replicas: %s, MinReplicas: %s, MaxReplicas: %s, Schedule: %s" % (deployment, namespace, replicas, minReplicas, maxReplicas, schedule)) with open("/root/schedule_scaling/templates/deployment-script.py", 'r') as script: script = script.read() deployment_script = script % { 'namespace': namespace, 'name': deployment, 'replicas': replicas, 'minReplicas': minReplicas, 'maxReplicas': maxReplicas, 'time': EXECUTION_TIME, } i = 0 while os.path.exists("/tmp/scaling_jobs/%s-%s.py" % (deployment, i)): i += 1 script_creator = open("/tmp/scaling_jobs/%s-%s.py" % (deployment, i), "w") script_creator.write(deployment_script) script_creator.close() cmd = ['sleep 50 ; . /root/.profile ; /usr/bin/python', script_creator.name, '2>&1 | tee -a /tmp/scale_activities.log'] cmd = ' '.join(map(str, cmd)) scaling_cron = CronTab(user='root') job = scaling_cron.new(command=cmd) try: job.setall(schedule) job.set_comment("Scheduling_Jobs") scaling_cron.write() except Exception: print('Deployment: %s has syntax error in the schedule' % (deployment)) pass