def delete(time, unit): cron = CronTab(user=True) if not exists(time, unit): print(f"Cannot delete. Cron entry: '{time}, {unit}' doesnt exist") return cron_time = convert(time, unit) cron_string = get_cron_line(time, unit) cron_string = cron_string.replace("*", "[*]") iter = cron.find_time(cron_time) for job in iter: cron.remove(job) cron.write() log.debug(f"Deleted from cron: {cron_string}")
def main(): module = AnsibleModule( argument_spec=dict( # default value for user to bypass required_one_of check # incase of validate_cron_time user=dict(default="dpal"), tabfile=dict(), use_regex=dict(default=False), match_string=dict(), schedule=dict(), list_all_crons=dict(type=bool), get_crons_by_command=dict(type=bool), get_crons_by_comment=dict(type=bool), get_crons_by_time=dict(type=bool), validate_cron_time=dict(type=bool), ), required_one_of=(("user", "tabfile"), ), required_if=( ("get_crons_by_command", True, ["match_string", "use_regex"]), ("get_crons_by_comment", True, ["match_string", "use_regex"]), ("get_crons_by_time", True, ["match_string", "use_regex"]), ("validate_cron_time", True, ["schedule"]), )) cron = CronTab(user=module.params["user"], tabfile=module.params["tabfile"]) if module.params['list_all_crons']: crons = cron.lines elif module.params['get_crons_by_command']: if module.params["use_regex"]: crons = cron.find_command( re.compile(r"{}".format(module.params["match_string"]))) else: crons = cron.find_command(module.params["match_string"]) elif module.params['get_crons_by_comment']: if module.params["use_regex"]: crons = cron.find_comment( re.compile(r"{}".format(module.params["match_string"]))) else: crons = cron.find_comment(module.params["match_string"]) elif module.params['get_crons_by_time']: crons = cron.find_time(module.params["match_string"]) elif module.params['validate_cron_time']: module.exit_json(valid=CronSlices.is_valid(module.params["schedule"])) else: module.fail_json(msg="unknown parameters") module.exit_json(crons=cron_items_to_list(crons))
def exists(time, unit): cron = CronTab(user=True) cron_time = convert(time, unit) iter = cron.find_time(cron_time) for x in iter: return True
from crontab import CronTab PATH_TO_SYSTEM_TAB_FILE = "data.tab" cron_obj = CronTab(tabfile=PATH_TO_SYSTEM_TAB_FILE) commands = cron_obj.find_command("client.py") for com in commands: print(com) commands = cron_obj.find_time("0 0 * * */3") for com in commands: print(com)