How to run and check cron jobs on Amazon Linux 2 using EC2

Trying to figure out if your cronjobs are running? Don’t even know how to run cronjobs at all? Here’s an easy way to get started.

How to run cronjobs

  1. Prepare the project/script locally
    • Create a Docker file in your local project
      • This will make it effortless to run your project without thinking about versions and requirements
      • Docker is not that hard to learn
    • Create a requirements.txt file in your local project
    • Push it to Git/Github
      • This is how we will get the project to our server easily
  2. Start your EC2 instance
    • Amazon Linux 2
      • Whatever settings you want, but the basics will be fine.
  3. Create a SSH in Github https://github.com/settings/keys
  4. Create a directory for the project
  5. Clone the project from git/Github
  6. Install crontab with sudo yum install cronie
  7. Open Cron using crontab -e
  8. Enter your cron command with the docker file you want to run
    • {* time instructions *} cd ~/directory && docker run -d project

How to check if cronjob ran successfully

Personally, I don’t want to be emailed every time a job runs. I have emails send if something breaks, but otherwise, I will assume things are ok.

At the time of this writing, ChatGPT says to look in a var/log/cron file which doesn’t exist. However, in the log directory, there is a REAME file that explains how the Journal works as a replacement for traditional log files.

You can use journalctl to navigate the journal & the logs it contains. journalctl man will show you the manual, while journalctl -u cron will give all cron logs. This is all very overwhelming and we don’t care.

You can search for cron logs using journalctl with grep

Using the command journalctl | grep "project" , you can search the logs by the name of the project you want to run.

If successful, you will see logs of cron executions; a CMD and then CMDEND log:

Jan 29 05:00:02 ip.user_name.internal CROND[000505]: (user_name) CMDEND (cd ~/directory && docker run -d project)

馃帀

Other possible errors

Here are some errors I made that maybe you did too:

  • incorrect naming of project or directory
  • incorrect cron time / cron set up
  • forgetting to save cron file
  • improperly setting up docker
  • improperly setting up SSH key

Closing Remarks

This took me way too long to figure out. Hope this helps!

How to run and check cron jobs on Amazon Linux 2 using EC2

Posted

in

by

Tags:

Comments

Leave a Reply

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