Best practices for implementing tasks that run via CRON


Best practices for implementing tasks that run via CRON

There are numerous blogs on the web on how to schedule a task to run as CRON job. However, we have not been able to find a single blog that talks about what points need to be kept in mind while implementing command that can be run via CRON. This blog is an attempt to do the same.

CRON jobs are scheduled jobs that run-in background and execute in background in linux / unix based systems. Any command/ job can be setup to be run via cron at a predefined interval. However, when implementing CRON jobs there are a few things that we should be kept in mind:

  1. CRON job, like any other process in unix based systems needs to give return code. It is based on this return code the OS decides if the process was successful or it failed with an error.
    • A return code of 0 is interpreted as Success
    • Any other integer return code (other than 0) is interpreted as ‘Failure’

Always use correct exit code for the process that you are implementing to be run as CRON job. In case there can be multiple scenarios that can lead to different types of errors, you should use different exit codes for each scenario so that based on exit code you will know what went wrong. The exit code for the process is captured in CRON related log file, as well as email is sent based on the same, if email is configured for CRON jobs.

2. A lot of times it is observed that, for a web application, developers implement the feature that can be executed via URL, as that makes it easy to execute and view the output in the browser. This may work well for development, however, CRON jobs should always be implemented as command line programs and the request should not be routed via web server.

Doing this helps in the following ways:

  • It does not unnecessarily add traffic to web server and reduces processing load / time.
    • A lot of times tasks scheduled to run via CRON take time much longer than any web request should take. If the request is routed via web server it unnecessarily blocks a thread with internal process.
    • Error logging and reporting can be managed much better via command line process.
    • If you are looking at process manager (top command) to diagnose which process is causing performance bottlenecks, if the CRON job runs via web server, it reflects as web process on performance report and it becomes difficult to diagnose which specific process is eating up the CUP time.

If you keep these things in mind when implementing task that are scheduled to run via CRON, you can monitor CRON logs to ensure that your tasks are running perfectly.

Leave a Reply

Your email address will not be published. Required fields are marked *