Skip to content

Instantly share code, notes, and snippets.

@lunohodov
Last active August 25, 2021 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lunohodov/f63e4e83f6dbbb159e6831d4521f0969 to your computer and use it in GitHub Desktop.
Save lunohodov/f63e4e83f6dbbb159e6831d4521f0969 to your computer and use it in GitHub Desktop.
A scheduler script to locally mimic Heroku's Scheduler

./bin/scheduler

A scheduler script to locally mimic Heroku's Scheduler.

You may find the script useful if

  • you have a Rails app and deploy on Heroku
  • during development, you need to locally run jobs at scheduled time intervals
  • you use a Procfile-based app manager such as Foreman

Usage

  1. Copy scheduler.sh as bin/scheduler and make it executable
  2. Copy scheduler.rake to lib/tasks/
  3. Add scheduler: ./bin/scheduler to your Procfile.dev

Then run the app with

foreman start -f Procfile.dev 

In addition you may do so with a script i.e bin/up

#!/bin/sh
foreman start -f Procfile.dev
# Meant to loosely mimic Heroku's Scheduler API
namespace :scheduler do
desc "All the tasks that need to run every 10 minutes"
task every_10_minutes: []
desc "All the tasks that need to run every hour"
task hourly: []
desc "All the tasks that need to run every day"
task daily: [
:"task1",
:"namespace:task1"
]
end
#!/usr/bin/env bash
run_task() {
task_name=$1
echo "Running task: $task_name"
# The --trace flag will tell Rake to log the name of
# each task it executes
bundle exec rails "$task_name" --trace
}
current_minute() {
date +%M
}
current_hour() {
date +%H
}
main() {
start_minute=$(current_minute)
start_hour=$(current_hour)
while true; do
minutes=$(current_minute)
hours=$(current_hour)
echo "Checking at time: $hours:$minutes"
# 10#$var helps avoid unwanted octal number interpolations
if [[ $((10#$minutes % 10)) -eq $start_minute ]];then
run_task scheduler:every_10_minutes
fi
if [[ $((10#$minutes)) -eq $start_minute ]];then
run_task scheduler:hourly
# Add 1 hour to avoid slow-down when booting the development server
if [[ $((10#$hours)) -eq $((10#$start_hour + 1)) ]];then
run_task scheduler:daily
fi
fi
sleep 60
done
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment