Search code examples
linuxubuntucronraspbian

How to move a file to cron.d in Linux?


my_cron-file works when it's created directly in /etc/cron.d/:

sudo nano /etc/cron.d/my_cron

# Add content:
* * * * * username /path/to/python /path/to/file 2>/path/to/log

But it doesn't work when I copy/move it to the directory:

sudo cp ./my_cron /etc/cron.d/my_cron

ls -l /etc/cron.d outputs the same permissions both times: -rw-r--r--. The files are owned by root.

The only reason I could imagine at the moment is that I've to refresh/activate something after copying, which happens automatically on creation.

Tested on Ubuntu and Raspbian.

Any idea? Thanks!


Solution

  • Older cron daemons used to examine /etc/cron.d for updated content only when they saw that the last-modified timestamp of that directory, or of the /etc/crontab file, had changed since the last time cron scanned it. Recent cron daemons also examine the timestamps of the individual files in /etc/cron.d but maybe you're dealing with an old one here.

    If you have an old cron, then if you copied a brand new file into /etc/cron.d then the directory's timestamp should change and cron should notice the new file. However, if your cp was merely overwriting an existing file then that would not change the directory timestamp and cron would not pick up the new file content.

    Editing a file in-place in /etc/cron.d would not necessarily update the directory timestamp, but some editors (certainly vi, unless you've configured it otherwise) will create temporary working files and perhaps a backup file in the directory where the file being edited lives. The creation and deletion of those other files will cause the directory timestamp to be updated, and that will cause cron to put the edited file into effect. This could explain why editing behaves differently for you than cp'ing does.

    To force a timestamp to be updated you could do something like sudo touch /etc/crontab or create and immediately remove a scratch file (or a directory) in /etc/cron.d after you've cp'ed or rm'ed a file in there. Obviously touch is easier. If you want to go the create+delete route then mktemp would be a good tool to use for that, in order to avoid clobbering someone else's legitimate file.

    If you were really paranoid, you'd wait at least a second between making file changes and then doing whatever you choose to do to force a timestamp update. That should avoid the situation where a cron rescan, your file updates, and your touch or scratch create+delete could all happen within the granularity of the timestamp.

    If you want to see what your cron is actually doing, you can sudo strace -p <pid-of-cron>. Mostly it sleeps for a minute at a time, but you'll see it stat some files and directories (including /etc/crontab and /etc/cron.d) each time it wakes up. And of course if it decides that it needs to run a job, you'll see that activity too.