I’m a big fan of monitoring my services. I like receiving emails about how well my architecture is running. To do that, I need to run tasks at specific times. And you’ve already guessed, I use cronjobs.
Cronjobs are particularly useful when you need to trigger a script at a specific interval. To setup cronjobs, you have several options. Each has its pros and cons. In this post, I’ll show you how to easily setup cronjobs with GitLab (for free my friends, keep your money to buy me a drink 🍹 ).
First, let’s see other options
Before diving in Gitlab, let me show you others options.
1. Buy you own server
You can buy a server in any provider (I personally recommend OVH, starting from 3€/month, best deal!). It’s cheap, but you have to configure everything !
2. Cronjobs As A Service
Websites provide cronjobs with logs, nice interface, email notifications …
- cron-job.org: All free
- easycron: Free version is very limited. But paid plans may suit your needs
- Google Cloud Scheduler: 3 free cronjobs/month, then $0.10/month/job. Perfect, especially if you already run other Google Cloud Products.
And finally, …
The trick to get cronjob for free with GitLab is to use its CI/CD service and the schedule panel.
If you want to know more about GitLab CI/CD, jump into the documentation here. It is very well explained.
If you are in a rush, let’s be straightforward:
- create a
.gitlab-ci.ymlfile at the root of your project (which must be under Gitlab… Of course)
- add a job with the script you want to be executed
- AND add a unique environment variable, like
- if: $CRON_NAME == "PING"
- curl -X GET https://www.google.com
- echo "All done here."
This environment variable is set to ensure that this job will not be triggered by something else (commit, merge request…).
Once this is file is set, open the GitLab repo in your favorite browser. Jump into the CI/CD section, and select “Schedules”. Click on the green button: “New schedule”.
Here, you can setup
- the interval pattern
- target branch (not important if you cronjobs is not based on your code)
- and Variables
In the Variables section, make sure to put the one you wrote into you .gitlab-ci.yml file.
If you have several cronjobs to run that are not project dependent, I recommend you to create a repo only for you cron jobs. Then, if the number of cronjobs increases, I can only recommend you to get a proper service to manage that (log, notifications, retry….).
In this post, we saw how to easily setup a cronjob for free with GitLab. The trick is to use GitLab CI/CD and the schedule.
If you start to have an important number of jobs to run, you may consider having a dedicated service to manage that.
I hope you have learnt something. If you have any remark, comments or improvements to share, feel free. Always ears opened to progress and to learn.