Poor Man's Cron Trigger

Published on .

This is a handy trick I use when I want to execute something as root when some event triggers, but without any interaction between the event and the start of the action. It’s quite unsafe and dirty, but it gets the job done.

When the event happens, make it create a file:

touch /tmp/this-event-happened

Now add the following cronjob as root (or whatever user you want):

* * * * * /bin/rm /tmp/this-event-happened 2>/dev/null && /bin/bash\

First come the stars, which tell cronjob to execute this command every minute. Then we try to remove the /tmp/this-event-happened file. rm will exit with an error-code when the file doesn’t exist, and in that case the script won’t be executed, because we’re chaining it using “&&”, the AND operator. In a shell, and most modern programming languages, if the first parameter of an AND operator is false, it won’t even evaluate the second parameter, because the total result will definetly be false anyway.

If the file does exist, the shell will evaluate the second parameter as well, and thus execute the script. Meanwhile the file will be removed, so everything is set up for the next trigger.

As you can see, very simple. It has some problems though. For example, any user can create files in /tmp, so it’s not very safe. You could create a directory somewhere that’s only accessible to the user that is allowed to generate the event, and put the trigger-file there. Another disadvantage: if the script takes longer than a minute to run, and the event is triggered again, the script will run twice at the same time. So take care when using this!

David Verhasselt

Senior full-stack engineer with 5 years of experience building web applications for clients all over the world.

Interested in working together?

Find out what I can do for you or get in touch!

Like this? Sign up to get regular updates