{"id":13878275,"url":"https://github.com/Rykian/clockwork","last_synced_at":"2025-07-16T14:31:54.439Z","repository":{"id":43309054,"uuid":"70566638","full_name":"Rykian/clockwork","owner":"Rykian","description":"A scheduler process to replace cron.","archived":false,"fork":true,"pushed_at":"2023-10-31T13:18:38.000Z","size":364,"stargazers_count":536,"open_issues_count":38,"forks_count":64,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-05-17T20:44:51.348Z","etag":null,"topics":["cron","scheduling"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"adamwiggins/clockwork","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Rykian.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-10-11T07:18:10.000Z","updated_at":"2024-05-06T19:53:59.000Z","dependencies_parsed_at":"2023-02-08T20:30:31.536Z","dependency_job_id":null,"html_url":"https://github.com/Rykian/clockwork","commit_stats":null,"previous_names":[],"tags_count":44,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rykian%2Fclockwork","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rykian%2Fclockwork/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rykian%2Fclockwork/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Rykian%2Fclockwork/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Rykian","download_url":"https://codeload.github.com/Rykian/clockwork/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":226138849,"owners_count":17579496,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cron","scheduling"],"created_at":"2024-08-06T08:01:44.831Z","updated_at":"2024-11-24T07:30:56.442Z","avatar_url":"https://github.com/Rykian.png","language":"Ruby","funding_links":[],"categories":["Ruby"],"sub_categories":[],"readme":"Clockwork - a clock process to replace cron [![Build Status](https://api.travis-ci.com/Rykian/clockwork.svg?branch=master)](https://travis-ci.org/Rykian/clockwork)\n===========================================\n\nCron is non-ideal for running scheduled application tasks, especially in an app\ndeployed to multiple machines.  [More details.](http://adam.herokuapp.com/past/2010/4/13/rethinking_cron/)\n\nClockwork is a cron replacement.  It runs as a lightweight, long-running Ruby\nprocess which sits alongside your web processes (Mongrel/Thin) and your worker\nprocesses (DJ/Resque/Minion/Stalker) to schedule recurring work at particular\ntimes or dates.  For example, refreshing feeds on an hourly basis, or send\nreminder emails on a nightly basis, or generating invoices once a month on the\n1st.\n\nQuickstart\n----------\n\nCreate clock.rb:\n\n```ruby\nrequire 'clockwork'\nrequire 'active_support/time' # Allow numeric durations (eg: 1.minutes)\n\nmodule Clockwork\n  handler do |job|\n    puts \"Running #{job}\"\n  end\n\n  # handler receives the time when job is prepared to run in the 2nd argument\n  # handler do |job, time|\n  #   puts \"Running #{job}, at #{time}\"\n  # end\n\n  every(10.seconds, 'frequent.job')\n  every(3.minutes, 'less.frequent.job')\n  every(1.hour, 'hourly.job')\n\n  every(1.day, 'midnight.job', :at =\u003e '00:00')\nend\n```\n\nRun it with the clockwork executable:\n\n```\n$ clockwork clock.rb\nStarting clock for 4 events: [ frequent.job less.frequent.job hourly.job midnight.job ]\nTriggering frequent.job\n```\n\nIf you need to load your entire environment for your jobs, simply add:\n\n```ruby\nrequire './config/boot'\nrequire './config/environment'\n```\n\nunder the `require 'clockwork'` declaration.\n\nQuickstart for Heroku\n---------------------\n\nClockwork fits well with heroku's cedar stack.\n\nConsider using [clockwork-init.sh](https://gist.github.com/tomykaira/1312172) to create\na new project for Heroku.\n\nUse with queueing\n-----------------\n\nThe clock process only makes sense as a place to schedule work to be done, not\nto do the work.  It avoids locking by running as a single process, but this\nmakes it impossible to parallelize.  For doing the work, you should be using a\njob queueing system, such as\n[Delayed Job](http://www.therailsway.com/2009/7/22/do-it-later-with-delayed-job),\n[Beanstalk/Stalker](http://adam.herokuapp.com/past/2010/4/24/beanstalk_a_simple_and_fast_queueing_backend/),\n[RabbitMQ/Minion](http://adam.herokuapp.com/past/2009/9/28/background_jobs_with_rabbitmq_and_minion/),\n[Resque](http://github.com/blog/542-introducing-resque), or\n[Sidekiq](https://github.com/mperham/sidekiq).  This design allows a\nsimple clock process with no locks, but also offers near infinite horizontal\nscalability.\n\nFor example, if you're using Beanstalk/Stalker:\n\n```ruby\nrequire 'stalker'\nrequire 'active_support/time'\n\nmodule Clockwork\n  handler { |job| Stalker.enqueue(job) }\n\n  every(1.hour, 'feeds.refresh')\n  every(1.day, 'reminders.send', :at =\u003e '01:30')\nend\n```\n\nUsing a queueing system which doesn't require that your full application be\nloaded is preferable, because the clock process can keep a tiny memory\nfootprint.  If you're using DJ or Resque, however, you can go ahead and load\nyour full application environment, and use per-event blocks to call DJ or Resque\nenqueue methods.  For example, with DJ/Rails:\n\n```ruby\nrequire 'config/boot'\nrequire 'config/environment'\n\nevery(1.hour, 'feeds.refresh') { Feed.send_later(:refresh) }\nevery(1.day, 'reminders.send', :at =\u003e '01:30') { Reminder.send_later(:send_reminders) }\n```\n\nUse with database events\n-----------------------\n\nIn addition to managing static events in your `clock.rb`, you can configure clockwork to synchronise with dynamic events from a database. Like static events, these database-backed events say when they should be run, and how frequently; the difference being that if you change those settings in the database, they will be reflected in clockwork.\n\nTo keep the database events in sync with clockwork, a special manager class `DatabaseEvents::Manager` is used. You tell it to sync a database-backed model using the `sync_database_events` method, and then, at the frequency you specify, it will fetch all the events from the database, and ensure clockwork is using the latest settings.\n\n### Example `clock.rb` file\n\nHere we're using an `ActiveRecord` model called `ClockworkDatabaseEvent` to store events in the database:\n\n```ruby\nrequire 'clockwork'\nrequire 'clockwork/database_events'\nrequire_relative './config/boot'\nrequire_relative './config/environment'\n\nmodule Clockwork\n\n  # required to enable database syncing support\n  Clockwork.manager = DatabaseEvents::Manager.new\n\n  sync_database_events model: ClockworkDatabaseEvent, every: 1.minute do |model_instance|\n\n    # do some work e.g...\n\n    # running a DelayedJob task, where #some_action is a method\n    # you've defined on the model, which does the work you need\n    model_instance.delay.some_action\n\n    # performing some work with Sidekiq\n    YourSidekiqWorkerClass.perform_async\n  end\n\n  [other events if you have]\n\nend\n```\n\nThis tells clockwork to fetch all `ClockworkDatabaseEvent` instances from the database, and create an internal clockwork event for each one. Each clockwork event will be configured based on the instance's `frequency` and, optionally, its `at`, `if?`, `ignored_attributes`, `name`, and, `tz` methods. The code above also says to reload the events from the database every `1.minute`; we need pick up any changes in the database frequently (choose a sensible reload frequency by changing the `every:` option).\n\nWhen one of the events is ready to be run (based on it's `frequency`, and possible `at`, `if?`, `ignored attributes`, and `tz` methods), clockwork arranges for the block passed to `sync_database_events` to be run. The above example shows how you could use either DelayedJob or Sidekiq to kick off a worker job. This approach is good because the ideal is to use clockwork as a simple scheduler, and avoid making it carry out any long-running tasks.\n\n### Your Model Classes\n\n`ActiveRecord` models are a perfect candidate for the model class. Having said that, the only requirements are:\n\n1. the class responds to `all` returning an array of instances from the database\n\n2. the instances returned respond to:\n   - `id` returning a unique identifier (this is needed to track changes to event settings)\n   - `frequency` returning the how frequently (in seconds) the database event should be run\n\n   - `attributes` returning a hash of [attribute name] =\u003e [attribute value] values (or really anything that we can use store on registering the event, and then compare again to see if the state has changed later)\n\n   - `at` *(optional)* return any acceptable clockwork `:at` string\n\n   - `name` *(optional)* returning the name for the event (used to identify it in the Clockwork output)\n\n   - `if?`*(optional)*  returning either true or false, depending on whether the database event should run at the given time (this method will be passed the time as a parameter, much like the standard clockwork `:if`)\n\n   - `ignored_attributes` *(optional)* returning an array of model attributes (as symbols) to ignore when determining whether the database event has been modified since our last run\n\n   - `tz` *(optional)* returning the timezone to use (default is the local timezone)\n\n   - `skip_first_run` *(optional)* self explanatory, see [dedicated section](#skip_first_run)\n\n#### Example Setup\n\nHere's an example of one way of setting up your ActiveRecord models:\n\n```ruby\n# db/migrate/20140302220659_create_frequency_periods.rb\nclass CreateFrequencyPeriods \u003c ActiveRecord::Migration\n  def change\n    create_table :frequency_periods do |t|\n      t.string :name\n\n      t.timestamps\n    end\n  end\nend\n\n# 20140302221102_create_clockwork_database_events.rb\nclass CreateClockworkDatabaseEvents \u003c ActiveRecord::Migration\n  def change\n    create_table :clockwork_database_events do |t|\n      t.integer :frequency_quantity\n      t.references :frequency_period\n      t.string :at\n\n      t.timestamps\n    end\n    add_index :clockwork_database_events, :frequency_period_id\n  end\nend\n\n# app/models/clockwork_database_event.rb\nclass ClockworkDatabaseEvent \u003c ActiveRecord::Base\n  belongs_to :frequency_period\n  attr_accessible :frequency_quantity, :frequency_period_id, :at\n\n  # Used by clockwork to schedule how frequently this event should be run\n  # Should be the intended number of seconds between executions\n  def frequency\n    frequency_quantity.send(frequency_period.name.pluralize)\n  end\nend\n\n# app/models/frequency_period.rb\nclass FrequencyPeriod \u003c ActiveRecord::Base\n  attr_accessible :name\nend\n\n# db/seeds.rb\n...\n# creating the FrequencyPeriods\n[:second, :minute, :hour, :day, :week, :month].each do |period|\n  FrequencyPeriod.create(name: period)\nend\n...\n```\n\n#### Example use of `if?`\n\nDatabase events support the ability to run events if certain conditions are met. This can be used to only run events on a given day, week, or month, or really any criteria you could conceive. Best of all, these criteria e.g. which day to\nrun it on can be attributes on your Model, and therefore change dynamically as you change the Model in the database.\n\nSo for example, if you had a Model that had a `day` and `month` integer attribute, you could specify that the Database event should only run on a particular day of a particular month as follows:\n\n```ruby\n# app/models/clockwork_database_event.rb\nclass ClockworkDatabaseEvent \u003c ActiveRecord::Base\n\n  ...\n\n  def if?(time)\n    time.day == day \u0026\u0026 time.month == month\n  end\n\n  ...\nend\n```\n\n#### Example use of `ignored_attributes`\n\nClockwork compares all attributes of the model between runs to determine if the model has changed, and if it has, it runs the event if all other conditions are met.\n\nHowever, in certain cases, you may want to store additional attributes in your model that you don't want to affect whether a database event is executed prior to its next interval.\n\nSo for example, you may update an attribute of your model named `last_scheduled_at` on each run to track the last time it was successfully scheduled. You can tell Clockwork to ignore that attribute in its comparison as follows:\n\n```ruby\n# app/models/clockwork_database_event.rb\nclass ClockworkDatabaseEvent \u003c ActiveRecord::Base\n\n  ...\n\n  def ignored_attributes\n    [ :last_scheduled_at ]\n  end\n\n  ...\nend\n```\n\n\nEvent Parameters\n----------\n\n### :at\n\n`:at` parameter specifies when to trigger the event:\n\n#### Valid formats:\n\n    HH:MM\n     H:MM\n    **:MM\n    HH:**\n    (Mon|mon|Monday|monday) HH:MM\n\n#### Examples\n\nThe simplest example:\n\n```ruby\nevery(1.day, 'reminders.send', :at =\u003e '01:30')\n```\n\nYou can omit the leading 0 of the hour:\n\n```ruby\nevery(1.day, 'reminders.send', :at =\u003e '1:30')\n```\n\nWildcards for hour and minute are supported:\n\n```ruby\nevery(1.hour, 'reminders.send', :at =\u003e '**:30')\nevery(10.seconds, 'frequent.job', :at =\u003e '9:**')\n```\n\nYou can set more than one timing:\n\n```ruby\nevery(1.day, 'reminders.send', :at =\u003e ['12:00', '18:00'])\n# send reminders at noon and evening\n```\n\nYou can specify the day of week to run:\n\n```ruby\nevery(1.week, 'myjob', :at =\u003e 'Monday 16:20')\n```\n\nIf another task is already running at the specified time, clockwork will skip execution of the task with the `:at` option.\nIf this is a problem, please use the `:thread` option to prevent the long running task from blocking clockwork's scheduler.\n\n### :tz\n\n`:tz` parameter lets you specify a timezone (default is the local timezone):\n\n```ruby\nevery(1.day, 'reminders.send', :at =\u003e '00:00', :tz =\u003e 'UTC')\n# Runs the job each day at midnight, UTC.\n# The value for :tz can be anything supported by [TZInfo](https://github.com/tzinfo/tzinfo)\n# Using the 'tzinfo' gem, run TZInfo::Timezone.all_identifiers to get a list of acceptable identifiers.\n```\n\n### :if\n\n`:if` parameter is invoked every time the task is ready to run, and run if the\nreturn value is true.\n\nRun on every first day of month.\n\n```ruby\nClockwork.every(1.day, 'myjob', :if =\u003e lambda { |t| t.day == 1 })\n```\n\nThe argument is an instance of `ActiveSupport::TimeWithZone` if the `:tz` option is set. Otherwise, it's an instance of `Time`.\n\nThis argument cannot be omitted.  Please use _ as placeholder if not needed.\n\n```ruby\nClockwork.every(1.second, 'myjob', :if =\u003e lambda { |_| true })\n```\n\n### :thread\n\nBy default, clockwork runs in a single-process and single-thread.\nIf an event handler takes a long time, the main routine of clockwork is blocked until it ends.\nClockwork does not misbehave, but the next event is blocked, and runs when the process is returned to the clockwork routine.\n\nThe `:thread` option is to avoid blocking. An event with `thread: true` runs in a different thread.\n\n```ruby\nClockwork.every(1.day, 'run.me.in.new.thread', :thread =\u003e true)\n```\n\nIf a job is long-running or IO-intensive, this option helps keep the clock precise.\n\n### :skip_first_run\n\nNormally, a clockwork process that is defined to run in a specified period will run at startup.\nThis is sometimes undesired behaviour, if the action being run relies on other processes booting which may be slower than clock.\nTo avoid this problem, `:skip_first_run` can be used.\n\n```ruby\nClockwork.every(5.minutes, 'myjob', :skip_first_run =\u003e true)\n```\n\nThe above job will not run at initial boot, and instead run every 5 minutes after boot.\n\n\nConfiguration\n-----------------------\n\nClockwork exposes a couple of configuration options:\n\n### :logger\n\nBy default Clockwork logs to `STDOUT`. In case you prefer your\nown logger implementation you have to specify the `logger` configuration option. See example below.\n\n### :sleep_timeout\n\nClockwork wakes up once a second and performs its duties. To change the number of seconds Clockwork\nsleeps, set the `sleep_timeout` configuration option as shown below in the example.\n\nFrom 1.1.0, Clockwork does not accept `sleep_timeout` less than 1 seconds.\n\n### :tz\n\nThis is the default timezone to use for all events.  When not specified this defaults to the local\ntimezone.  Specifying :tz in the parameters for an event overrides anything set here.\n\n### :max_threads\n\nClockwork runs handlers in threads. If it exceeds `max_threads`, it will warn you (log an error) about missing\njobs.\n\n\n### :thread\n\nBoolean true or false. Default is false. If set to true, every event will be run in its own thread. Can be overridden on a per event basis (see the ```:thread``` option in the Event Parameters section above)\n\n### Configuration example\n\n```ruby\nmodule Clockwork\n  configure do |config|\n    config[:sleep_timeout] = 5\n    config[:logger] = Logger.new(log_file_path)\n    config[:tz] = 'EST'\n    config[:max_threads] = 15\n    config[:thread] = true\n  end\nend\n```\n\n### error_handler\n\nYou can add error_handler to define your own logging or error rescue.\n\n```ruby\nmodule Clockwork\n  error_handler do |error|\n    Airbrake.notify_or_ignore(error)\n  end\nend\n```\n\nCurrent specifications are as follows.\n\n- defining error_handler does not disable original logging\n- errors from error_handler itself are not rescued, and stop clockwork\n\nAny suggestion about these specifications is welcome.\n\nOld style\n---------\n\n`include Clockwork` is old style.\nThe old style is still supported, though not recommended, because it pollutes the global namespace.\n\n\n\nAnatomy of a clock file\n-----------------------\n\nclock.rb is standard Ruby.  Since we include the Clockwork module (the\nclockwork executable does this automatically, or you can do it explicitly), this\nexposes a small DSL to define the handler for events, and then the events themselves.\n\nThe handler typically looks like this:\n\n```ruby\nhandler { |job| enqueue_your_job(job) }\n```\n\nThis block will be invoked every time an event is triggered, with the job name\npassed in.  In most cases, you should be able to pass the job name directly\nthrough to your queueing system.\n\nThe second part of the file, which lists the events, roughly resembles a crontab:\n\n```ruby\nevery(5.minutes, 'thing.do')\nevery(1.hour, 'otherthing.do')\n```\n\nIn the first line of this example, an event will be triggered once every five\nminutes, passing the job name 'thing.do' into the handler.  The handler shown\nabove would thus call enqueue_your_job('thing.do').\n\nYou can also pass a custom block to the handler, for job queueing systems that\nrely on classes rather than job names (i.e. DJ and Resque).  In this case, you\nneed not define a general event handler, and instead provide one with each\nevent:\n\n```ruby\nevery(5.minutes, 'thing.do') { Thing.send_later(:do) }\n```\n\nIf you provide a custom handler for the block, the job name is used only for\nlogging.\n\nYou can also use blocks to do more complex checks:\n\n```ruby\nevery(1.day, 'check.leap.year') do\n  Stalker.enqueue('leap.year.party') if Date.leap?(Time.now.year)\nend\n```\n\nIn addition, Clockwork also supports `:before_tick`, `:after_tick`, `:before_run`, and `:after_run` callbacks.\nAll callbacks are optional. All `before` callbacks must return a truthy value otherwise the job will not run. The `tick` callbacks run every tick (a tick being whatever your `:sleep_timeout`\nis set to, default is 1 second):\n\n```ruby\non(:before_tick) do\n  puts \"tick\"\nend\n\non(:after_tick) do\n  puts \"tock\"\nend\n\non(:before_run) do |event, t|\n  puts \"job_started: #{event}\"\nend\n\non(:after_run) do |event, t|\n  puts \"job_finished: #{event}\"\nend\n```\n\nFinally, you can use tasks synchronised from a database as described in detail above:\n\n```ruby\nsync_database_events model: MyEvent, every: 1.minute do |instance_job_name|\n  # what to do with each instance\nend\n```\n\nYou can use multiple `sync_database_events` if you wish, so long as you use different model classes for each (ActiveRecord Single Table Inheritance could be a good idea if you're doing this).\n\nIn production\n-------------\n\nOnly one clock process should ever be running across your whole application\ndeployment.  For example, if your app is running on three VPS machines (two app\nservers and one database), your app machines might have the following process\ntopography:\n\n* App server 1: 3 web (thin start), 3 workers (rake jobs:work), 1 clock (clockwork clock.rb)\n* App server 2: 3 web (thin start), 3 workers (rake jobs:work)\n\nYou should use [Monit](http://mmonit.com/monit/), [God](https://github.com/mojombo/god), [Upstart](http://upstart.ubuntu.com/), or [Inittab](http://www.tldp.org/LDP/sag/html/config-init.html) to keep your clock process\nrunning the same way you keep your web and workers running.\n\nDaemonization\n-------------\n\nThanks to @fddayan, `clockworkd` executes clockwork script as a daemon.\n\nYou will need the [daemons gem](https://github.com/ghazel/daemons) to use `clockworkd`.  It is not automatically installed, please install by yourself.\n\nThen,\n\n```\nclockworkd -c YOUR_CLOCK.rb start\n```\n\nFor more details, you can run `clockworkd -h`.\n\nIntegration Testing\n-------------------\n\nYou could take a look at:\n* [clockwork-mocks](https://github.com/dpoetzsch/clockwork-mocks) that helps with running scheduled tasks during integration testing.\n* [clockwork-test](https://github.com/kevin-j-m/clockwork-test) which ensures that tasks are triggered at the right time\n\nIssues and Pull requests\n------------------------\n\nIf you find a bug, please create an issue - [Issues · Rykian/clockwork](https://github.com/Rykian/clockwork/issues).\n\nFor a bug fix or a feature request, please send a pull-request.\nDo not forget to add tests to show how your feature works, or what bug is fixed.\nAll existing tests and new tests must pass (TravisCI is watching).\n\nWe want to provide simple and customizable core, so superficial changes will not be merged (e.g. supporting new event registration style).\nIn most cases, directly operating `Manager` realizes an idea, without touching the core.\nIf you discover a new way to use Clockwork, please create a gist page or an article on your website, then add it to the following \"Use cases\" section.\nThis tool is already used in various environment, so backward-incompatible requests will be mostly rejected.\n\nUse cases\n---------\n\nFeel free to add your idea or experience and send a pull-request.\n\n- Sending errors to Airbrake\n- Read events from a database\n\nMeta\n----\n\nCreated by Adam Wiggins\n\nInspired by [rufus-scheduler](https://github.com/jmettraux/rufus-scheduler) and [resque-scheduler](https://github.com/bvandenbos/resque-scheduler)\n\nDesign assistance from Peter van Hardenberg and Matthew Soldo\n\nPatches contributed by Mark McGranaghan and Lukáš Konarovský\n\nReleased under the MIT License: http://www.opensource.org/licenses/mit-license.php\n\nhttps://github.com/Rykian/clockwork\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRykian%2Fclockwork","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FRykian%2Fclockwork","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRykian%2Fclockwork/lists"}