Skip to content

Instantly share code, notes, and snippets.

@LarryWachira
Last active March 17, 2021 04:31
Show Gist options
  • Save LarryWachira/9860252b22fa514a54e5f92b3aeefcc9 to your computer and use it in GitHub Desktop.
Save LarryWachira/9860252b22fa514a54e5f92b3aeefcc9 to your computer and use it in GitHub Desktop.
Working with python-crontab
import os
import sys
from crontab import CronTab # naturally, this needs to be pip installed
def cronjobs(delete=False):
"""Add or remove cron jobs"""
cron = CronTab(user=True)
success_ops_comment = 'success ops weekly pending logged activities' \
' newsletter'
if delete:
cron.remove_all(comment=success_ops_comment)
cron.write()
print('\n\n>>>>> Cron jobs removed successfully\n\n')
sys.exit()
# remove existing cron jobs with the same exact comment
print(f'\n\n>>>>> Removing older \'{success_ops_comment}\' cron jobs')
cron.remove_all(comment=success_ops_comment)
base_dir = os.path.dirname(__file__)
success_ops_news_job = cron.new(
command=f'$(which python) {base_dir}/manage.py '
f'>> {base_dir}/cron.txt',
comment=success_ops_comment
)
success_ops_news_job.every(1).minute()
cron.write()
print('\n\n>>>>> Cron jobs initiated successfully\n\n')
sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment