README.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. Python Crontab
  2. --------------
  3. .. image:: https://gitlab.com/doctormo/python-crontab/raw/master/branding.svg
  4. .. image:: https://badge.fury.io/py/python-crontab.svg
  5. :target: https://badge.fury.io/py/python-crontab
  6. .. image:: https://img.shields.io/badge/License-LGPL%20v3-blue.svg
  7. :target: https://gitlab.com/doctormo/python-crontab/raw/master/COPYING
  8. Bug Reports and Development
  9. ===========================
  10. Please report any problems to the `GitLab issues tracker <https://gitlab.com/doctormo/python-crontab/issues>`_. Please use Git and push patches to the `GitLab project code hosting <https://gitlab.com/doctormo/python-crontab>`_.
  11. **Note:** If you get the error ``TypeError: __init__() takes exactly 2 arguments`` when using CronTab, you have the wrong module installed. You need to install ``python-crontab`` and not ``crontab`` from pypi or your local package manager and try again.
  12. Description
  13. ===========
  14. Crontab module for reading and writing crontab files and accessing the system cron
  15. automatically and simply using a direct API.
  16. Comparing the `below chart <http://en.wikipedia.org/wiki/Cron#CRON_expression>`_
  17. you will note that W, L, # and ? symbols are not supported as they are not
  18. standard Linux or SystemV crontab format.
  19. +-------------+-----------+-----------------+-------------------+-------------+
  20. |Field Name |Mandatory |Allowed Values |Special Characters |Extra Values |
  21. +=============+===========+=================+===================+=============+
  22. |Minutes |Yes |0-59 |\* / , - | < > |
  23. +-------------+-----------+-----------------+-------------------+-------------+
  24. |Hours |Yes |0-23 |\* / , - | < > |
  25. +-------------+-----------+-----------------+-------------------+-------------+
  26. |Day of month |Yes |1-31 |\* / , - | < > |
  27. +-------------+-----------+-----------------+-------------------+-------------+
  28. |Month |Yes |1-12 or JAN-DEC |\* / , - | < > |
  29. +-------------+-----------+-----------------+-------------------+-------------+
  30. |Day of week |Yes |0-6 or SUN-SAT |\* / , - | < > |
  31. +-------------+-----------+-----------------+-------------------+-------------+
  32. Extra Values are '<' for minimum value, such as 0 for minutes or 1 for months.
  33. And '>' for maximum value, such as 23 for hours or 12 for months.
  34. Supported special cases allow crontab lines to not use fields.
  35. These are the supported aliases which are not available in SystemV mode:
  36. =========== ============
  37. Case Meaning
  38. =========== ============
  39. @reboot Every boot
  40. @hourly 0 * * * *
  41. @daily 0 0 * * *
  42. @weekly 0 0 * * 0
  43. @monthly 0 0 1 * *
  44. @yearly 0 0 1 1 *
  45. @annually 0 0 1 1 *
  46. @midnight 0 0 * * *
  47. =========== ============
  48. How to Use the Module
  49. =====================
  50. **Note:** Several users have reported their new crontabs not saving automatically or that the module doesn't do anything. You **MUST** use write() if you want your edits to be saved out. See below for full details on the use of the write function.
  51. Getting access to a crontab can happen in five ways, three system methods that
  52. will work only on Unix and require you to have the right permissions::
  53. from crontab import CronTab
  54. empty_cron = CronTab()
  55. my_user_cron = CronTab(user=True)
  56. users_cron = CronTab(user='username')
  57. And two ways from non-system sources that will work on Windows too::
  58. file_cron = CronTab(tabfile='filename.tab')
  59. mem_cron = CronTab(tab="""
  60. * * * * * command
  61. """)
  62. Special per-command user flag for vixie cron format (new in 1.9)::
  63. system_cron = CronTab(tabfile='/etc/crontab', user=False)
  64. job = system_cron[0]
  65. job.user != None
  66. system_cron.new(command='new_command', user='root')
  67. Creating a new job is as simple as::
  68. job = cron.new(command='/usr/bin/echo')
  69. And setting the job's time restrictions::
  70. job.minute.during(5,50).every(5)
  71. job.hour.every(4)
  72. job.day.on(4, 5, 6)
  73. job.dow.on('SUN')
  74. job.dow.on('SUN', 'FRI')
  75. job.month.during('APR', 'NOV')
  76. Each time restriction will clear the previous restriction::
  77. job.hour.every(10) # Set to * */10 * * *
  78. job.hour.on(2) # Set to * 2 * * *
  79. Appending restrictions is explicit::
  80. job.hour.every(10) # Set to * */10 * * *
  81. job.hour.also.on(2) # Set to * 2,*/10 * * *
  82. Setting all time slices at once::
  83. job.setall(2, 10, '2-4', '*/2', None)
  84. job.setall('2 10 * * *')
  85. Setting the slice to a python date object::
  86. job.setall(time(10, 2))
  87. job.setall(date(2000, 4, 2))
  88. job.setall(datetime(2000, 4, 2, 10, 2))
  89. Run a jobs command. Running the job here will not effect it's
  90. existing schedule with another crontab process::
  91. job_standard_output = job.run()
  92. Creating a job with a comment::
  93. job = cron.new(command='/foo/bar', comment='SomeID')
  94. Get the comment or command for a job::
  95. command = job.command
  96. comment = job.comment
  97. Modify the comment or command on a job::
  98. job.set_command("new_script.sh")
  99. job.set_comment("New ID or comment here")
  100. Disabled or Enable Job::
  101. job.enable()
  102. job.enable(False)
  103. False == job.is_enabled()
  104. Validity Check::
  105. True == job.is_valid()
  106. Use a special syntax::
  107. job.every_reboot()
  108. Find an existing job by command sub-match or regular expression::
  109. iter = cron.find_command('bar') # matches foobar1
  110. iter = cron.find_command(re.compile(r'b[ab]r$'))
  111. Find an existing job by comment exact match or regular expression::
  112. iter = cron.find_comment('ID or some text')
  113. iter = cron.find_comment(re.compile(' or \w'))
  114. Find an existing job by schedule::
  115. iter = cron.find_time(2, 10, '2-4', '*/2', None)
  116. iter = cron.find_time("*/2 * * * *")
  117. Clean a job of all rules::
  118. job.clear()
  119. Iterate through all jobs, this includes disabled (commented out) cron jobs::
  120. for job in cron:
  121. print job
  122. Iterate through all lines, this includes all comments and empty lines::
  123. for line in cron.lines:
  124. print line
  125. Remove Items::
  126. cron.remove( job )
  127. cron.remove_all('echo')
  128. cron.remove_all(comment='foo')
  129. cron.remove_all(time='*/2')
  130. Clear entire cron of all jobs::
  131. cron.remove_all()
  132. Write CronTab back to system or filename::
  133. cron.write()
  134. Write CronTab to new filename::
  135. cron.write( 'output.tab' )
  136. Write to this user's crontab (unix only)::
  137. cron.write_to_user( user=True )
  138. Write to some other user's crontab::
  139. cron.write_to_user( user='bob' )
  140. Validate a cron time string::
  141. from crontab import CronSlices
  142. bool = CronSlices.is_valid('0/2 * * * *')
  143. Environment Variables
  144. =====================
  145. Some versions of vixie cron support variables outside of the command line.
  146. Sometimes just update the envronment when commands are run, the Cronie fork
  147. of vixie cron also supports CRON_TZ which looks like a regular variable but
  148. actually changes the times the jobs are run at.
  149. Very old vixie crons don't support per-job variables, but most do.
  150. Iterate through cron level environment variables::
  151. for (name, value) in cron.env.items():
  152. print name
  153. print value
  154. Create new or update cron level environment variables::
  155. print cron.env['SHELL']
  156. cron.env['SHELL'] = '/bin/bash'
  157. print cron.env
  158. Each job can also have a list of environment variables::
  159. for job in cron:
  160. job.env['NEW_VAR'] = 'A'
  161. print job.env
  162. Proceeding Unit Confusion
  163. =========================
  164. It is sometimes logical to think that job.hour.every(2) will set all proceeding
  165. units to '0' and thus result in "0 \*/2 * * \*". Instead you are controlling
  166. only the hours units and the minute column is unaffected. The real result would
  167. be "\* \*/2 * * \*" and maybe unexpected to those unfamiliar with crontabs.
  168. There is a special 'every' method on a job to clear the job's existing schedule
  169. and replace it with a simple single unit::
  170. job.every(4).hours() == '0 */4 * * *'
  171. job.every().dom() == '0 0 * * *'
  172. job.every().month() == '0 0 0 * *'
  173. job.every(2).dows() == '0 0 * * */2'
  174. This is a convenience method only, it does normal things with the existing api.
  175. Running the Scheduler
  176. =====================
  177. The module is able to run a cron tab as a daemon as long as the optional
  178. croniter module is installed; each process will block and errors will
  179. be logged (new in 2.0).
  180. (note this functionality is new and not perfect, if you find bugs report them!)
  181. Running the scheduler::
  182. tab = CronTab(tabfile='MyScripts.tab')
  183. for result in tab.run_scheduler():
  184. print "This was printed to stdout by the process."
  185. Do not do this, it won't work because it returns generator function::
  186. tab.run_scheduler()
  187. Timeout and cadence can be changed for testing or error management::
  188. for result in tab.run_scheduler(timeout=600):
  189. print "Will run jobs every 1 minutes for ten minutes from now()"
  190. for result in tab.run_scheduler(cadence=1, warp=True):
  191. print "Will run jobs every 1 second, counting each second as 1 minute"
  192. Frequency Calculation
  193. =====================
  194. Every job's schedule has a frequency. We can attempt to calculate the number
  195. of times a job would execute in a give amount of time. We have three simple
  196. methods::
  197. job.setall("1,2 1,2 * * *")
  198. job.frequency_per_day() == 4
  199. The per year frequency method will tell you how many days a year the
  200. job would execute::
  201. job.setall("* * 1,2 1,2 *")
  202. job.frequency_per_year(year=2010) == 4
  203. These are combined to give the number of times a job will execute in any year::
  204. job.setall("1,2 1,2 1,2 1,2 *")
  205. job.frequency(year=2010) == 16
  206. Frequency can be quickly checked using python built-in operators::
  207. job < "*/2 * * * *"
  208. job > job2
  209. job.slices == "*/5"
  210. Log Functionality
  211. =================
  212. The log functionality will read a cron log backwards to find you the last run
  213. instances of your crontab and cron jobs.
  214. The crontab will limit the returned entries to the user the crontab is for::
  215. cron = CronTab(user='root')
  216. for d in cron.log:
  217. print d['pid'] + " - " + d['date']
  218. Each job can return a log iterator too, these are filtered so you can see when
  219. the last execution was::
  220. for d in cron.find_command('echo')[0].log:
  221. print d['pid'] + " - " + d['date']
  222. All System CronTabs Functionality
  223. =================================
  224. The crontabs (note the plural) module can attempt to find all crontabs on the
  225. system. This works well for Linux systems with known locations for cron files
  226. and user spolls. It will even extract anacron jobs so you can get a picture
  227. of all the jobs running on your system::
  228. from crontabs import CronTabs
  229. for cron in CronTabs():
  230. print repr(cron)
  231. All jobs can be brought together to run various searches, all jobs are added
  232. to a CronTab object which can be used as documented above::
  233. jobs = CronTabs().all.find_command('foo')
  234. Schedule Functionality
  235. ======================
  236. If you have the croniter python module installed, you will have access to a
  237. schedule on each job. For example if you want to know when a job will next run::
  238. schedule = job.schedule(date_from=datetime.now())
  239. This creates a schedule croniter based on the job from the time specified. The
  240. default date_from is the current date/time if not specified. Next we can get
  241. the datetime of the next job::
  242. datetime = schedule.get_next()
  243. Or the previous::
  244. datetime = schedule.get_prev()
  245. The get methods work in the same way as the default croniter, except that they
  246. will return datetime objects by default instead of floats. If you want the
  247. original functionality, pass float into the method when calling::
  248. datetime = schedule.get_current(float)
  249. If you don't have the croniter module installed, you'll get an ImportError when
  250. you first try using the schedule function on your cron job object.
  251. Descriptor Functionality
  252. ========================
  253. If you have the cron-descriptor module installed, you will be able to ask for a
  254. translated string which describes the frequency of the job in the current
  255. locale language. This should be mostly human readable.
  256. print(job.description(use_24hour_time_format=True))
  257. See cron-descriptor for details of the supported languages and options.
  258. Extra Support
  259. =============
  260. - Support for vixie cron with username addition with user flag
  261. - Support for SunOS, AIX & HP with compatibility 'SystemV' mode.
  262. - Python 3.5.2 and Python 2.7 tested, python 2.6 removed from support.
  263. - Windows support works for non-system crontabs only.
  264. ( see mem_cron and file_cron examples above for usage )