GITHUB
Published: 03.2024
Views: 128
>_ How to Run Scheduled Cron Jobs in GitHub Workflows for Free
Learn how to automate recurring tasks using GitHub Actions workflows. This guide covers setting up cron jobs, handling scheduled tasks, and leveraging GitHub's free tier effectively.
Running Scheduled Tasks with GitHub Actions
As a programmer, there are often tasks that need to be run on a regular schedule, such as syncing data from an API, sending notifications, or generating reports. GitHub Actions provides a powerful way to automate these tasks for free!
Understanding GitHub Actions Workflow
name: Monthly Sync DB
on:
schedule:
- cron: '0 0 1 * *' # Runs at 00:00 UTC on the 1st day of every month
workflow_dispatch:
jobs:
syncDB:
runs-on: ubuntu-latest
permissions:
# Give the GITHUB_TOKEN write permission to commit changes
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install dependencies
run: npm ci
- name: Run sync-db.js
run: node src/utils/sync-db.js
- name: Commit and push changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: Update shows.json
file_pattern: src/data/shows.json
commit_options: '--no-verify --signoff'
Let's break down the key components:
1. Schedule Definition
- Uses cron syntax for timing
- Runs at 00:00 UTC on the 1st day of every month
- Allows manual trigger with workflow_dispatch
2. Job Configuration
- Runs on latest Ubuntu
- Sets up proper permissions
- Manages Node.js environment
3. Step Execution
- Checks out code
- Sets up Node.js
- Installs dependencies
- Runs sync script
- Commits changes
Benefits of This Approach
- Zero Infrastructure Cost: Runs on GitHub's servers
- Built-in Version Control: Changes are tracked in your repository
- Easy Monitoring: Built-in logging and status checks
- Flexible Scheduling: Use cron syntax for precise timing
- Manual Override: Can be triggered manually when needed
Best Practices
- Set appropriate permissions
- Handle errors gracefully
- Use meaningful commit messages
- Monitor execution logs
- Test thoroughly before scheduling
Remember, GitHub Actions provides a generous free tier that's perfect for most automation needs!
TAGS:
TUTORIAL
WORKFLOW
GITHUB ACTIONS