Github as Cron
Table of Contents
Introduction #
In this article, I will be sharing how to run your cronjobs within Github itself. This can have many other extensions which can go beyond just running cronjobs.
We will also be setting up a simple cronjob to run every hour to demonstrate how it works.
How does it work? #
The idea is to use Github Actions to run your cronjobs. Github Actions is a CI/CD tool that allows you to automate your workflow. It is very flexible and can be used to run any kind of task.
There is actually a schedule
event that you can use to run your cronjobs.
Here is an example of how you can use it:
name: My Cron Jobs
on:
schedule:
- cron: "0 * * * *" # Schedule to run the job on
workflow_dispatch: # This is to allow you to run the job manually
jobs:
my-cron-job:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: main
- name: Run my cron job
run: ./cronjob.sh
- name: Update repo with new data
uses: stefanzweifel/git-auto-commit-action@v5 # This is to commit the changes to the repo
with:
commit_message: automated update
In this example, the cronjob will run every hour.
This can be run in combination with other actions to do more complex tasks.
The auto commit
action can trigger the ci when a commit is made to the repo.
Project #
In this project, I will be building a project that does the following
- Scrape xkcd comics every day
- Publish the the image and data onto a static site
There will be 2 main parts of the CI for this project.
- The cronjob to scrape xkcd
- The CI to publish the posts onto a static site
To view the full project, you can view it here
How does it work? #
When the schedule is triggered, the cronjob will run the python script to scrape the xkcd comics. After writing the information into the repository, the cronjob makes a commit to the repo.
The Github Pages action will then be triggered to publish the site. After the deployment is completed, the site will be updated with the new comic row.
To view the live project, you can view it here
Conclusion #
In this article, I have shared how to use Github Actions to run your cronjobs. This can be used to run any kind of task and can be used to automate your workflow. Some additional ideas for using this includes the following:
- Health Check for websites
- Running tests on websites
- Running backups
- Running data collection
- Send scheduled notifications
- Run a polling bot that consolidates information every minute
Note: Github free tier only allows for 2000 minutes of CI/CD per month. This means that you can only run the cronjob for 2000 minutes per month. This is a limitation that you should be aware of when using Github Actions as a cronjob replacement.
To get higher limits, you can upgrade to github pro. To read more about the pricing, you can view it here