Many CMS services rely on Cron jobs to manage their automated tasks; these jobs are often configured to run every five minutes or sooner to ensure that tasks are completed in time.

However, if a cron job that has been run fails to complete before the next instance of the cron job is run, this may result in unnecessary processes running for your user, which in many cases are not removed and can result in increased usage.

To avoid this occurring, you can change a cron job to run under flock; this is a process that will ensure only one version of a cron job can ever be running at once.

Take the following job as an example:

/usr/local/bin/php /home/brixlymonitoring/public_html/artisan schedule:run >> /dev/null 2>&1

This is a cron job that we would commonly see with Magento and often results in additional processes running where two jobs are running at once.

We can alter this to include flock by changing it to the following:

flock -n /home/brixlymonitoring/tmp/schedule.lock /usr/local/bin/php /home/brixlymonitoring/public_html/artisan schedule:run >> /dev/null 2>&1

The cron job is now being run by the flock command; this will create a lock file under the tmp folder and then run the cron job.

When the job is completed, the lock file is removed.

When the job next runs, it will check if the lock file exists; if so, the job is prevented from running.