### Install Project Dependencies Source: https://github.com/javan/whenever/blob/main/CONTRIBUTING.md Run this command to install all necessary Ruby gems for the project. Ensure you have Bundler installed. ```bash $ bundle install ``` -------------------------------- ### Install Whenever Gem Source: https://github.com/javan/whenever/blob/main/README.md Install the Whenever gem using the RubyGems package manager. ```sh $ gem install whenever ``` -------------------------------- ### Show Whenever Version Source: https://context7.com/javan/whenever/llms.txt Displays the currently installed version of the Whenever gem. This is useful for checking compatibility or reporting issues. ```sh # Show version $ bundle exec whenever --version # Whenever v1.1.2 ``` -------------------------------- ### Deploy.rb Configuration for System-Wide Rbenv Source: https://github.com/javan/whenever/wiki/rbenv-and-capistrano-Notes Configure rbenv settings in deploy.rb for system-wide installations. This sets the rbenv path, type, Ruby version, and maps executable bins. ```ruby ## # Rbenv Setup set :rbenv_custom_path, '/opt/rbenv' set :rbenv_type, :system set :rbenv_ruby, '2.3.2' rbenv_prefix = [ "RBENV_ROOT=#{fetch(:rbenv_path)}", "RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec" ] set :rbenv_prefix, rbenv_prefix.join(' ') set :rbenv_map_bins, %w(rake gem bundle ruby rails) set :bundle_binstubs, -> { shared_path.join('bin') } # Configure 'whenever' vars = lambda do "'environment=#{fetch :whenever_environment}" "&rbenv_root=#{fetch :rbenv_custom_path}" "&rbenv_version=#{fetch :rbenv_ruby}'" end set :whenever_variables, vars ``` -------------------------------- ### Install Crontab for Specific User with `whenever --user` Source: https://context7.com/javan/whenever/llms.txt Installs or updates the crontab for a specified system user. This is useful in multi-user environments or when deploying to a specific service account. ```sh # Install for a specific system user $ bundle exec whenever --update-crontab --user deploy ``` -------------------------------- ### Scheduling a Rake Task Every 30 Minutes Source: https://context7.com/javan/whenever/llms.txt This example shows how to schedule a Rake task to run every 30 minutes using the Whenever DSL. The output indicates the generated cron syntax. ```ruby every 30.minutes do rake "cache:warm" end # => */30 * * * * (every 30 minutes, at :00 and :30) ``` -------------------------------- ### Scheduling a Rake Task Every 6 Hours Source: https://context7.com/javan/whenever/llms.txt This example demonstrates scheduling a Rake task to run every 6 hours. The generated cron syntax is provided as a comment. ```ruby every 6.hours do rake "reports:generate" end # => 0 */6 * * * (at midnight, 6am, noon, 6pm) ``` -------------------------------- ### Update Crontab with `whenever --update-crontab` Source: https://context7.com/javan/whenever/llms.txt Installs or updates the system crontab non-destructively by wrapping new entries in labeled comment blocks. This allows multiple projects to coexist safely. ```sh # Install / update crontab non-destructively (wraps entries in labeled comment block) $ bundle exec whenever --update-crontab ``` -------------------------------- ### Configure Chronic Parser Options Source: https://github.com/javan/whenever/blob/main/README.md Customize the date/time parsing behavior of the Chronic gem used by Whenever, for example, to enforce 24-hour clock. ```ruby set :chronic_options, hours24: true # By default this would run the job every day at 3am every 1.day, at: '3:00' do runner "MyModel.nightly_archive_job" end ``` -------------------------------- ### Bootstrap Schedule File with `wheneverize` Source: https://context7.com/javan/whenever/llms.txt Initializes a project by creating a commented `config/schedule.rb` template. This command is safe to run on existing projects as it skips creation if the file already exists. ```sh # Bootstrap a new Rails app $ cd /apps/my-great-project $ bundle exec wheneverize . # [add] writing `config/schedule.rb' # [done] wheneverized! # Resulting config/schedule.rb template: # Use this file to easily define all of your cron jobs. # # set :output, "/path/to/my/cron_log.log" # # every 2.hours do # command "/usr/bin/some_great_command" # runner "MyModel.some_method" # rake "some:great:rake:task" # end ``` -------------------------------- ### Initialize Whenever Configuration Source: https://github.com/javan/whenever/blob/main/README.md Generate the initial `schedule.rb` configuration file in your project's config directory. ```sh $ cd /apps/my-great-project $ bundle exec wheneverize . ``` -------------------------------- ### Deploy.rb Configuration using rbenv exec Source: https://github.com/javan/whenever/wiki/rbenv-and-capistrano-Notes Alternative deploy.rb configuration for whenever that utilizes 'rbenv exec' for task execution. It sets the whenever environment and identifier. ```ruby # Whenever config set :whenever_environment, fetch(:stage) set :whenever_identifier, "#{fetch(:application)}_#{fetch(:stage)}" set :whenever_variables, -> do "'environment=#{fetch :whenever_environment}" "&rbenv_root=#{fetch :rbenv_path}'" end ``` -------------------------------- ### Run Project Tests Source: https://github.com/javan/whenever/blob/main/CONTRIBUTING.md Execute this command to run the test suite for the Whenever project. This is typically done after making code changes or to verify the current state. ```bash $ make test ``` -------------------------------- ### Use Custom Schedule File with `whenever --load-file` Source: https://context7.com/javan/whenever/llms.txt Specifies a custom schedule file to load instead of the default `config/schedule.rb`. This is useful for managing multiple schedules or testing. ```sh # Use a custom schedule file $ bundle exec whenever --load-file config/my_schedule.rb ``` -------------------------------- ### Preview Crontab Output with `whenever` Source: https://context7.com/javan/whenever/llms.txt Prints a preview of the generated cron syntax without modifying the system crontab. This is useful for verifying the schedule before deployment. ```sh # Preview the generated cron output (does NOT modify crontab) $ bundle exec whenever # 0 0 * * * /bin/bash -l -c 'cd /apps/my-app && RAILS_ENV=production bundle exec rake cleanup --silent >> /dev/null 2>&1' # ## [message] Above is your schedule file converted to cron syntax; your crontab file was not updated. ``` -------------------------------- ### Schedule Jobs with Cron Keyword Shortcuts Source: https://context7.com/javan/whenever/llms.txt Uses cron keyword shortcuts like `:hour`, `:day`, `:month`, `:year`, or `:reboot` for scheduling. These cannot be combined with the `:at` option. ```ruby # Cron keyword shortcuts: :hour, :day, :month, :year, :reboot # (cannot be combined with :at) every :hour do runner "SomeModel.ladeeda" end ``` -------------------------------- ### Capistrano v3 Integration for Whenever Source: https://context7.com/javan/whenever/llms.txt Add to `Capfile`; tasks hook into `deploy:updated` and `deploy:reverted` automatically. Configure with `set` in `config/deploy.rb`. ```ruby # Capfile require "whenever/capistrano" ``` ```ruby # config/deploy.rb set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" } set :whenever_environment, ->{ fetch(:rails_env, fetch(:stage, "production")) } set :whenever_roles, ->{ :db } # default; set to array for multiple set :whenever_load_file, ->{ nil } # nil = use default config/schedule.rb set :whenever_update_flags, ->{ "--update-crontab #{fetch :whenever_identifier} --set #{fetch :whenever_variables}" } # Available tasks: # cap production whenever:update_crontab # cap production whenever:clear_crontab ``` -------------------------------- ### Capfile Configuration for Rbenv and Whenever Source: https://github.com/javan/whenever/wiki/rbenv-and-capistrano-Notes Include these lines in your Capfile to enable rbenv and whenever integration with Capistrano. ```ruby require 'capistrano/rbenv' require 'whenever/capistrano' ``` -------------------------------- ### Schedule.rb Configuration for Rbenv Source: https://github.com/javan/whenever/wiki/rbenv-and-capistrano-Notes Set the rbenv root path and version in schedule.rb to ensure whenever jobs run with the correct Ruby environment. ```ruby set :rbenv_root, '/opt/rbenv' set :rbenv_version, '2.3.3' env 'RBENV_ROOT', rbenv_root env 'RBENV_VERSION', rbenv_version ``` -------------------------------- ### Configure schedule variables with `set` in Whenever Source: https://context7.com/javan/whenever/llms.txt The `set` command configures global variables for path, environment, output redirection, and job templates. Command-line options override `set` configurations. ```ruby # config/schedule.rb # Override the default application path set :path, '/apps/my-great-project' # Change the Rails environment variable name and value set :environment_variable, "RAILS_ENV" set :environment, "production" # Redirect all job output globally set :output, '/var/log/cron.log' # Change the job wrapper template (default wraps in bash -l -c) set :job_template, "/bin/bash -l -c ':job'" # Disable the job template wrapper entirely set :job_template, nil # Configure 24-hour clock for Chronic time parsing set :chronic_options, hours24: true every 1.day, at: '15:30' do # parsed as 3:30pm in 24h mode runner "Report.generate" end ``` -------------------------------- ### View Cron Syntax Source: https://github.com/javan/whenever/blob/main/README.md Display the current `schedule.rb` file converted into cron syntax without modifying the crontab. ```sh $ cd /apps/my-great-project $ bundle exec whenever ``` -------------------------------- ### Configure Default Email Headers Source: https://github.com/javan/whenever/wiki/Sending-Emails Set default 'from', 'return_path', and 'sender' headers for email sending. This is often required to resolve 'ArgumentError' when sending messages. ```ruby default from: "Your Name ", return_path: 'your.name@example.com', sender: 'your.name@example.com' ``` -------------------------------- ### Run a Rake task with Whenever Source: https://context7.com/javan/whenever/llms.txt Use the `rake` job type to execute Rake tasks. It automatically prefixes commands with `bundle exec` if a Gemfile is present. ```ruby # config/schedule.rb every 1.day, at: '12:01 am' do rake "app:cleanup" end every 1.week do rake "db:backup" end ``` ```cron # Produces (with bundler, bin/rails present): # 1 0 * * * /bin/bash -l -c 'cd /apps/my-app && RAILS_ENV=production bundle exec rake app:cleanup --silent >> /dev/null 2>&1' ``` -------------------------------- ### Set Global Output Redirection for Error and Standard Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Configure global output redirection to separate files for standard output and errors. Ensure this setting precedes job definitions to function correctly. ```ruby # This works set :output, {:error => '~/Desktop/z.error.log', :standard => '~/Desktop/z.standard.log'} every 1.minute do command "python ~/Desktop/whe/config/z.py" end ``` -------------------------------- ### Set Whenever Command for Specific User Source: https://github.com/javan/whenever/wiki/Adding-jobs-to-another-users-crontab Add this configuration to your `deploy.rb` file to specify that Whenever jobs should be executed as the 'www-data' user. This ensures tasks run with the correct environment and permissions. ```ruby set :whenever_command, ->{ [:bundle, :exec, :whenever, '--user www-data'] } ``` -------------------------------- ### Separate Standard and Error Log Files Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Configure separate log files for standard output and errors using the 'output' variable with a hash. ```ruby # adds ">> cron.log 2> error.log" to all commands set :output, {:error => 'error.log', :standard => 'cron.log'} ``` -------------------------------- ### Make Rails Root and Environment Config Available Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Include this require statement to make `Rails.root` and other `Rails.application.config` values accessible within your cron job scripts. ```ruby # makes Rails.root as well as other environment specific Rails.application.config values available require File.expand_path(File.dirname(__FILE__) + "/environment") ``` -------------------------------- ### Configure Output Redirection in Whenever Source: https://context7.com/javan/whenever/llms.txt Control where stdout and stderr go using global `set :output` or per-job `output:` options. Accepts a String, Hash, nil, or Proc. ```ruby # config/schedule.rb # Global: append stdout and stderr to same file set :output, '/var/log/cron/my_app.log' # Global: suppress all output (equivalent to > /dev/null 2>&1) set :output, nil # Global: separate stdout and stderr set :output, standard: '/var/log/cron/cron.log', error: '/var/log/cron/cron.error.log' # Per-job override: log to specific file every 1.day, at: '3am' do runner "Archiver.run", output: '/var/log/cron/archiver.log' end # Per-job: discard stdout, keep stderr every 1.hour do command "/usr/bin/scraper", output: { standard: nil, error: '/var/log/scraper.err' } end # Per-job: custom Proc every 1.day do command "/usr/bin/cmd", output: -> { ">> /tmp/#{Date.today}.log 2>&1" } end # String output => >> /path/to/file.log 2>&1 # nil output => >> /dev/null 2>&1 # { standard: '/a', error: '/b' } => >> /a 2>> /b # { standard: nil, error: nil } => > /dev/null 2>&1 ``` -------------------------------- ### Schedule Jobs with Day-of-Week Shortcuts Source: https://context7.com/javan/whenever/llms.txt Schedules jobs based on specific days of the week using shortcuts like `:sunday` through `:saturday`, `:weekday`, or `:weekend`. Can be combined with the `:at` option. ```ruby # Day-of-week shortcuts: :sunday..:saturday, :weekday, :weekend every :sunday, at: '12pm' do runner "Task.do_something_great" end ``` -------------------------------- ### Add comments to crontab entries with `description:` in Whenever Source: https://context7.com/javan/whenever/llms.txt The `description:` option adds human-readable comments above generated cron lines, improving crontab self-documentation. Multi-line descriptions are supported. ```ruby # config/schedule.rb every 1.hour, description: "Clear expired cache entries" do command "/usr/bin/clear_cache.sh" end every 1.day, at: '2am', description: "Nightly DB backup\nStores to S3" do rake "db:backup" end ``` ```cron # Generated crontab: # # Clear expired cache entries # 0 * * * * /bin/bash -l -c '/usr/bin/clear_cache.sh' # # # Nightly DB backup # # Stores to S3 # 0 2 * * * /bin/bash -l -c 'cd /apps/my-app && RAILS_ENV=production bundle exec rake db:backup --silent' ``` -------------------------------- ### Scheduled Job: Using Raw Cron Syntax Source: https://github.com/javan/whenever/blob/main/README.md Define cron jobs using standard cron syntax for precise scheduling. ```ruby every '0 0 27-31 * *' do command "echo 'you can use raw cron syntax too'" end ``` -------------------------------- ### Set environment variables for specific environments in schedule.rb Source: https://github.com/javan/whenever/wiki/Troubleshooting Use the 'env' command in schedule.rb to set environment-specific variables, such as GEM_HOME, RUBY_LIB, and PATH. This is useful for managing different configurations across environments like production. ```ruby env 'GEM_HOME','/home/web_faction_username/webapps/web_faction_app_name/gems' ``` ```ruby env 'RUBY_LIB','/home/web_faction_username/webapps/web_faction_app_name/rails_root_dir/lib' ``` ```ruby env 'PATH','/home/web_faction_username/webapps/web_faction_app_name/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/web_faction_username/bin' ``` -------------------------------- ### Scheduled Job: Daily at Specific Time Source: https://github.com/javan/whenever/blob/main/README.md Schedule a job to run once daily at a precise time, like 4:30 AM. ```ruby every 1.day, at: '4:30 am' do runner "MyModel.task_to_run_at_four_thirty_in_the_morning" end ``` -------------------------------- ### Capistrano Configuration for Whenever Source: https://github.com/javan/whenever/wiki/RVM-Notes Configure Capistrano in `config/deploy.rb` to correctly set environment variables and commands for Whenever, ensuring it uses the appropriate paths and stages. ```ruby set :whenever_environment, defer { stage } set :whenever_identifier, defer { "#{application}_#{stage}" } set :whenever_command, "bundle exec whenever" set :whenever_variables, defer { "'environment=#{rails_env}¤t_path=#{current_path}'" } require 'whenever/capistrano' ``` -------------------------------- ### Use Rails Root for Log Directory Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Construct the log file path using `#{path}` (Whenever.path) to ensure logs are placed within the Rails application's log directory. ```ruby set :output, "#{path}/log/cron.log" ``` -------------------------------- ### Add Multi-Line Description to Crontab Entry Source: https://github.com/javan/whenever/blob/main/README.md Allows for multi-line descriptions to be added as comments above cron entries, providing more detailed explanations for complex jobs. ```ruby every 1.hours, description: "My job description\nhas multiple lines" do command "/usr/bin/my_great_command" end ``` -------------------------------- ### Run Shell Command with Output Redirection Source: https://context7.com/javan/whenever/llms.txt Schedules a shell command and redirects its output to a specified log file using the `output:` option. This is useful for capturing job output for debugging or auditing. ```ruby # With output redirection for this specific job every 1.day, at: '2am' do command "/usr/bin/cleanup.sh", output: '/var/log/cleanup.log' end # Produces cron entry: ``` -------------------------------- ### Basic Schedule: Every 3 Hours Source: https://github.com/javan/whenever/blob/main/README.md Define a job to run every 3 hours using runner, rake, or command tasks. Tasks run in parallel. ```ruby every 3.hours do # 1.minute 1.day 1.week 1.month 1.year is also supported # the following tasks are run in parallel (not in sequence) runner "MyModel.some_process" rake "my:rake:task" command "/usr/bin/my_great_command" end ``` -------------------------------- ### Run a Simple Shell Command Job Source: https://context7.com/javan/whenever/llms.txt Defines a scheduled job that executes a raw shell command. The `:task` placeholder is replaced by the command argument, and `:output` handles redirection. ```ruby # config/schedule.rb # Simple shell command every 1.hour do command "/usr/bin/my_great_command" end ``` -------------------------------- ### Capistrano V2 Integration with Alternative Schedule Path Source: https://github.com/javan/whenever/blob/main/README.md Configures Capistrano V2 to load the schedule from an alternative path instead of the default 'config/schedule.rb'. Requires 'whenever/capistrano' to be required. ```ruby set :whenever_load_file, defer { "#{release_path}/somewhere/else/schedule.rb" } require "whenever/capistrano" ``` -------------------------------- ### Schedule Jobs with Specific Time using `:at` Source: https://context7.com/javan/whenever/llms.txt Schedules jobs to run at a specific time of day, parsed by Chronic. The `:at` option accepts a string representing the time. ```ruby # With a specific :at time (parsed by Chronic) every 1.day, at: '4:30 am' do runner "MyModel.task_to_run_at_four_thirty_in_the_morning" end ``` -------------------------------- ### Set Custom Job Template Source: https://github.com/javan/whenever/blob/main/README.md Override the default job execution template, which uses `bash -l -c 'command...'` to ensure full environment loading. ```ruby set :job_template, "bash -l -c ':job'" ``` -------------------------------- ### Capistrano v2 Integration for Whenever Source: https://context7.com/javan/whenever/llms.txt Automatically updates the crontab after `deploy:update_code` and reverts on `deploy:rollback`. Configure with `_cset` variables before requiring the recipe. ```ruby # config/deploy.rb set :whenever_command, "bundle exec whenever" set :whenever_environment, defer { stage } # use Capistrano :stage variable set :whenever_identifier, defer { "#{application}_#{stage}" } # namespace per app+stage set :whenever_load_file, defer { "#{release_path}/config/schedule.rb" } # set :whenever_roles, [:db] # default require "whenever/capistrano" # Available Capistrano tasks: # cap whenever:update_crontab – update crontab on deploy # cap whenever:clear_crontab – remove all whenever crontab entries ``` ```ruby # config/deploy.rb (Capistrano v2) set :whenever_roles, [:db, :app] # must include all roles used in schedule.rb require "whenever/capistrano" ``` -------------------------------- ### Default Job Deployment Source: https://github.com/javan/whenever/blob/main/README.md By default, jobs are deployed to all servers in the whenever_roles list. Ensure the role is defined in deploy.rb. ```ruby every :day, at: '12:20am' do rake 'foo:bar' end ``` -------------------------------- ### Incorrect Placement of Global Output Redirection Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Demonstrates an incorrect placement of the global 'output' setting after job definitions, which will not be applied. ```ruby every 1.minute do command "python ~/Desktop/whe/config/z.py" end # This won't work set :output, {:error => '~/Desktop/z.error.log', :standard => '~/Desktop/z.standard.log'} ``` -------------------------------- ### Whenever Command Options Source: https://github.com/javan/whenever/blob/main/README.md Common options for the `whenever` command to specify user, load file, or override crontab command. ```sh $ whenever --user app ``` ```sh $ whenever --load-file config/my_schedule.rb ``` ```sh $ whenever --crontab-command 'sudo crontab' ``` -------------------------------- ### Schedule Jobs with Range-based Cron Syntax Source: https://context7.com/javan/whenever/llms.txt Uses ranges within cron syntax for day-of-month or hour specifications. This enables scheduling jobs for specific periods within a month or day. ```ruby # Range-based cron syntax for day-of-month / hours every '30 8 1-15 * *' do rake "billing:send_invoices" end ``` -------------------------------- ### Configure environment-specific settings in Capistrano deploy.rb Source: https://github.com/javan/whenever/wiki/Troubleshooting When using Whenever with Capistrano, you can define environment-specific configurations within your deploy.rb file using a case statement. This allows for tailored settings based on the deployment environment. ```ruby case @environment when 'production' ... end end ``` -------------------------------- ### Programmatic Cron Generation with Whenever.cron Source: https://context7.com/javan/whenever/llms.txt Generate cron output from a string or file without touching the crontab. Useful for testing, previewing, or custom deploy tooling. ```ruby require 'whenever' # Generate from an inline string output = Whenever.cron(string: <<~SCHEDULE) set :path, '/apps/my-app' every 1.day, at: '4:30 am' do runner "MyModel.some_process" end every :hour do command "/usr/bin/ping_monitor" end SCHEDULE puts output # 0 * * * * /bin/bash -l -c '/usr/bin/ping_monitor' # 30 4 * * * /bin/bash -l -c 'cd /apps/my-app && bundle exec bin/rails runner -e production\'MyModel.some_process\'' # Generate from a file output = Whenever.cron(file: 'config/schedule.rb') # Generate with pre-set variables (useful for staging vs. production) output = Whenever.cron( file: 'config/schedule.rb', set: 'environment=staging&path=/apps/staging', roles: [:app] ) # Programmatic crontab update (used by Capistrano integration) Whenever.update_cron( file: 'config/schedule.rb', identifier: 'my_app_production', set: 'environment=production' ) ``` -------------------------------- ### Update Crontab Source: https://github.com/javan/whenever/blob/main/README.md Write the generated cron syntax from `schedule.rb` to the system's crontab file. ```sh $ whenever --update-crontab ``` -------------------------------- ### Schedule Jobs Multiple Times Daily Source: https://context7.com/javan/whenever/llms.txt Defines jobs to run at multiple specific times within a single day. The `:at` option accepts an array of time strings. ```ruby # Multiple :at times in a single block every 1.day, at: ['4:30 am', '6:00 pm'] do runner "MyModel.task_twice_daily" end ``` -------------------------------- ### Capistrano V2 Integration with Staging/Production Environments Source: https://github.com/javan/whenever/blob/main/README.md Sets the Whenever environment to the Capistrano stage variable, allowing for environment-specific crontab configurations. Requires 'whenever/capistrano' to be required. ```ruby set :whenever_environment, defer { stage } require "whenever/capistrano" ``` -------------------------------- ### Redirect Output to /dev/null Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Explicitly set output redirection to '/dev/null' to discard all output from cron jobs. ```ruby # adds ">> /dev/null 2>&1" to all commands set :output, nil set :output, {:error => nil, :standard => nil} ``` -------------------------------- ### Schedule.rb Configuration using rbenv exec Source: https://github.com/javan/whenever/wiki/rbenv-and-capistrano-Notes Alternative schedule.rb configuration that defines job types using 'rbenv exec' for rake, runner, and script jobs. This ensures rbenv is correctly invoked for each job type. ```ruby # Whenever config if @rbenv_root job_type :rake, %{cd :path && :environment_variable=:environment :rbenv_root/bin/rbenv exec bundle exec rake :task --silent :output} job_type :runner, %{cd :path && :rbenv_root/bin/rbenv exec bundle exec rails runner -e :environment ':task' :output} job_type :script, %{cd :path && :environment_variable=:environment :rbenv_root/bin/rbenv exec bundle exec script/:task :output} end ``` -------------------------------- ### Role-Based Job Deployment Source: https://github.com/javan/whenever/blob/main/README.md Restrict jobs to specific servers by adding a `roles: [...]` argument. Jobs without a :roles argument are deployed to all servers in the whenever_roles list. ```ruby every :day, at: '1:37pm', roles: [:app] do rake 'app:task' # will only be added to crontabs of :app servers end ``` ```ruby every :hour, roles: [:db] do rake 'db:task' # will only be added to crontabs of :db servers end ``` ```ruby every :day, at: '12:02am' do command "run_this_everywhere" # will be deployed to :db and :app servers end ``` -------------------------------- ### Define a custom job type with Whenever Source: https://context7.com/javan/whenever/llms.txt Use `job_type` to register custom job types with template strings. Placeholders like `:task` and `:fun_level` are replaced with provided arguments or variables. ```ruby # config/schedule.rb # Define a custom job type job_type :awesome, '/usr/local/bin/awesome :task :fun_level' every 2.hours do awesome "party", fun_level: "extreme" end # Runs: /usr/local/bin/awesome party extreme # Custom job that uses standard placeholders job_type :python_script, "cd :path && :environment_variable=:environment python3 :task :output" every 1.day, at: '3am' do python_script "scripts/nightly_report.py" end # Runs: cd /apps/my-app && RAILS_ENV=production python3 scripts/nightly_report.py >> /dev/null 2>&1 ``` -------------------------------- ### Redirect Standard Output to /dev/null Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Discard only the standard output of cron jobs by redirecting it to '/dev/null'. ```ruby # adds ">> /dev/null" to all commands set :output, {:standard => nil} ``` -------------------------------- ### Configure Mailer with Default Email Headers Source: https://github.com/javan/whenever/wiki/Sending-Emails Define default email headers within an Action Mailer class. This ensures all emails sent from this mailer include the specified sender and return path. ```ruby class YourMailer < ActionMailer::Base helper :application default from: "Your Name ", return_path: 'your.name@example.com', sender: 'your.name@example.com' def your_mailer_email # your mailer logic end end ``` -------------------------------- ### Add Single Line Description to Crontab Entry Source: https://github.com/javan/whenever/blob/main/README.md Includes a single-line description as a comment above the cron entry in the crontab. This aids in identifying the purpose of the job. ```ruby every 1.hours, description: "My job description" do command "/usr/bin/my_great_command" end ``` -------------------------------- ### Default Job Type Definitions Source: https://github.com/javan/whenever/blob/main/README.md Examine the default definitions for built-in job types like command, rake, script, and runner. ```ruby job_type :command, ":task :output" job_type :rake, "cd :path && :environment_variable=:environment :bundle_command rake :task --silent :output" job_type :script, "cd :path && :environment_variable=:environment :bundle_command script/:task :output" job_type :runner, "cd :path && :bundle_command :runner_command -e :environment ':task' :output" ``` -------------------------------- ### Capistrano V2 Integration Source: https://github.com/javan/whenever/blob/main/README.md Integrates Whenever with Capistrano V2 for automated crontab updates during deployment. Requires 'whenever/capistrano' to be required. ```ruby require "whenever/capistrano" ``` -------------------------------- ### Scheduled Job: Shorthand for Hourly Source: https://github.com/javan/whenever/blob/main/README.md Use shorthand syntax to schedule jobs for common intervals like every hour. ```ruby every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot runner "SomeModel.ladeeda" end ``` -------------------------------- ### Command-Level Output Redirection Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Set output redirection options individually for specific commands, runners, or rake tasks. ```ruby every 3.hours do runner "MyModel.some_process", :output => 'cron.log' rake "my:rake:task", :output => {:error => 'error.log', :standard => 'cron.log'} command "/usr/bin/cmd" end ``` -------------------------------- ### Integrate Whenever with Capistrano deployment Source: https://github.com/javan/whenever/wiki/Troubleshooting Ensure Whenever runs after Bundler during Capistrano deployments by requiring the Capistrano recipes and defining 'whenever:update_crontab' tasks. This prevents issues where cron jobs try to run before dependencies are available. ```ruby #manual to influence later execution time #require 'whenever/capistrano' require 'whenever/capistrano/recipes' after "deploy:finalize_update", "whenever:update_crontab" after "deploy:rollback", "whenever:update_crontab" ``` -------------------------------- ### Capistrano V2 Integration with Bundler Source: https://github.com/javan/whenever/blob/main/README.md Configures Capistrano V2 to use 'bundle exec whenever' for crontab updates, ensuring jobs run within the correct bundle context. Requires 'whenever/capistrano' to be required. ```ruby set :whenever_command, "bundle exec whenever" require "whenever/capistrano" ``` -------------------------------- ### Set crontab environment variables with `env` in Whenever Source: https://context7.com/javan/whenever/llms.txt Use the `env` command to write `KEY=value` lines at the top of the generated crontab. This is commonly used for setting `MAILTO` globally. ```ruby # config/schedule.rb # Suppress all cron email output env 'MAILTO', '' # Or direct output to a specific address env 'MAILTO', 'alerts@example.com' env 'RAILS_ENV', 'production' every 3.hours do command "/usr/bin/my_great_command" end ``` ```cron # Generated crontab output: # MAILTO=alerts@example.com # RAILS_ENV=production # # 0 */3 * * * /bin/bash -l -c '/usr/bin/my_great_command' ``` -------------------------------- ### Configure MAILTO for Interval Block Source: https://github.com/javan/whenever/blob/main/README.md Sets a specific MAILTO address for all jobs defined within a particular time interval block. This allows for granular control over email recipients. ```ruby every 3.hours, mailto: 'my_super_command@example.com' do command "/usr/bin/my_super_command" end ``` -------------------------------- ### Pipe Output to a Command using Lambda Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Use a lambda to pipe the output of cron jobs to another command, such as `logger`, for further processing. ```ruby set :output, lambda { "2>&1 | logger -t whenever_cron" } ``` -------------------------------- ### Override Variables at Runtime with `whenever --set` Source: https://context7.com/javan/whenever/llms.txt Allows overriding variables defined in the schedule file at runtime. This is particularly useful for configuring different environments like staging or production. ```sh # Override variables at runtime (useful for staging) $ bundle exec whenever --update-crontab --set 'environment=staging&path=/apps/staging' ``` -------------------------------- ### Scheduled Job: Weekly on Specific Day Source: https://github.com/javan/whenever/blob/main/README.md Schedule a job to run on a specific day of the week, such as every Sunday at noon. ```ruby every :sunday, at: '12pm' do # Use any day of the week or :weekend, :weekday runner "Task.do_something_great" end ``` -------------------------------- ### Add Whenever to Gemfile Source: https://github.com/javan/whenever/blob/main/README.md Include Whenever as a dependency in your application's Gemfile for use with Bundler. ```ruby gem 'whenever', require: false ``` -------------------------------- ### Numeric Time Unit Helpers in Whenever Source: https://context7.com/javan/whenever/llms.txt Whenever extends `Numeric` to provide time-unit methods for integer literals, returning raw second counts for cron field translation. ```ruby require 'whenever' ``` -------------------------------- ### Run a Rails runner expression with Whenever Source: https://context7.com/javan/whenever/llms.txt The `runner` job type executes Ruby expressions using `bin/rails runner`. It automatically detects the correct runner command for your Rails version. ```ruby # config/schedule.rb every 1.day, at: '4:30 am' do runner "MyModel.some_process" end every :hour do runner "Cache.clear_expired_entries" end ``` ```cron # Produces: # 30 4 * * * /bin/bash -l -c 'cd /apps/my-app && bundle exec bin/rails runner -e production\'MyModel.some_process\'' >> /dev/null 2>&1' ``` -------------------------------- ### Scheduled Job: Multiple Times Daily Source: https://github.com/javan/whenever/blob/main/README.md Schedule a job to run at multiple specific times within a day. ```ruby every 1.day, at: ['4:30 am', '6:00 pm'] do runner "Mymodel.task_to_run_in_two_times_every_day" end ``` -------------------------------- ### Time Unit Definitions in Ruby Source: https://context7.com/javan/whenever/llms.txt Whenever defines convenient methods for time units, returning the equivalent number of seconds. These are often used internally or for clarity in schedule definitions. ```ruby 1.minute # => 60 5.minutes # => 300 1.hour # => 3600 3.hours # => 10800 1.day # => 86400 1.week # => 604800 1.month # => 2592000 1.year # => 31557600 ``` -------------------------------- ### Configure MAILTO for Single Job Source: https://github.com/javan/whenever/blob/main/README.md Assigns a specific MAILTO address to an individual job. This is useful when only a particular command's output needs to be emailed to a different address. ```ruby every 3.hours do command "/usr/bin/my_super_command", mailto: 'my_super_command_output@example.com' end ``` -------------------------------- ### Capistrano V2 Integration with Namespaced Environments Source: https://github.com/javan/whenever/blob/main/README.md Namespaces crontab entries by application and stage to prevent overwrites when deploying multiple environments to the same server. Requires 'whenever/capistrano' to be required. ```ruby set :whenever_environment, defer { stage } set :whenever_identifier, defer { "#{application}_#{stage}" } require "whenever/capistrano" ``` -------------------------------- ### Custom Job Types for Whenever Schedule Source: https://github.com/javan/whenever/wiki/RVM-Notes Define custom job types in `config/schedule.rb` to prepend a command that changes the directory to the application's current path, suppressing RVM output and ensuring correct execution context. ```ruby job_type :rake, "{ cd #{@current_path} > /dev/null; } && RAILS_ENV=:environment bundle exec rake :task --silent :output" job_type :script, "{ cd #{@current_path} > /dev/null; } && RAILS_ENV=:environment bundle exec script/:task :output" job_type :runner, "{ cd #{@current_path} > /dev/null; } && RAILS_ENV=:environment bundle exec rails runner ':task' :output" ``` -------------------------------- ### Redirect Errors to /dev/null Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Discard only the error output of cron jobs by redirecting it to '/dev/null'. ```ruby # adds "2> /dev/null" to all commands set :output, {:error => nil} ``` -------------------------------- ### Trust RVMrc Files Flag Source: https://github.com/javan/whenever/wiki/RVM-Notes Set this flag in your user `~/.rvmrc` file to automatically trust all RVMrc files, preventing prompts that can cause cron jobs to hang. ```bash rvm_trust_rvmrcs_flag=1 ``` -------------------------------- ### Disable Job Template Source: https://github.com/javan/whenever/blob/main/README.md Set the job template to `nil` to have jobs execute using the default cron environment without shell wrappers. ```ruby set :job_template, nil ``` -------------------------------- ### Override Crontab Command with `whenever --crontab-command` Source: https://context7.com/javan/whenever/llms.txt Specifies an alternative command for interacting with the crontab, such as using `sudo crontab`. This is useful when the default `crontab` command is not available or requires elevated privileges. ```sh # Override the crontab binary (e.g. sudo crontab) $ bundle exec whenever --crontab-command 'sudo crontab' ``` -------------------------------- ### Redirect Only Standard Output Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Redirect only the standard output of cron jobs to a specified log file. ```ruby # adds ">> cron.log" to all commands set :output, {:standard => 'cron.log'} ``` -------------------------------- ### Set PATH environment variable in schedule.rb Source: https://github.com/javan/whenever/wiki/Troubleshooting Configure the PATH environment variable within your schedule.rb file to ensure cron jobs can locate executables. This is an alternative to setting it directly in the crontab. ```ruby env :PATH, '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin' ``` ```ruby env :PATH, ENV['PATH'] ``` -------------------------------- ### Set Global Output Redirection Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Set the 'output' variable globally to redirect all cron job commands to a specified log file. This setting should appear before job definitions. ```ruby # adds ">> /path/to/file.log 2>&1" to all commands set :output, '/path/to/file.log' ``` -------------------------------- ### Per-block and per-job email overrides with `mailto:` in Whenever Source: https://context7.com/javan/whenever/llms.txt The `mailto:` option overrides the `MAILTO` environment variable for specific `every` blocks or individual jobs, allowing fine-grained email routing. ```ruby # config/schedule.rb # Per-block MAILTO every 3.hours, mailto: 'ops@example.com' do command "/usr/bin/my_super_command" end # Per-job MAILTO (overrides block-level) every 1.day, at: '6am' do command "/usr/bin/report.sh", mailto: 'reports@example.com' command "/usr/bin/cleanup.sh", mailto: '' # silence this one job end ``` ```cron # Generated crontab: # MAILTO=ops@example.com # 0 */3 * * * /bin/bash -l -c '/usr/bin/my_super_command' # # MAILTO=reports@example.com # 0 6 * * * /bin/bash -l -c '/usr/bin/report.sh' ``` -------------------------------- ### Define Scheduled Jobs with Numeric Durations Source: https://context7.com/javan/whenever/llms.txt Uses numeric durations like `1.minute`, `2.hours`, or `1.day` to define job frequencies. Jobs within the block run in parallel at the specified interval. ```ruby # config/schedule.rb # Numeric durations: 1.minute, 2.hours, 1.day, 1.week, 1.month, 1.year every 3.hours do command "/usr/bin/my_great_command" rake "my:rake:task" runner "MyModel.some_process" end ``` -------------------------------- ### Overwrite Crontab with `whenever --write-crontab` Source: https://context7.com/javan/whenever/llms.txt Completely overwrites the system crontab with only the entries defined in the schedule file. Use with caution as it removes any existing crontab entries not managed by Whenever. ```sh # Overwrite crontab entirely with only these entries $ bundle exec whenever --write-crontab ``` -------------------------------- ### Define Custom Job Type Source: https://github.com/javan/whenever/blob/main/README.md Create custom job types beyond the defaults (command, rake, runner) for specific command-line tools. ```ruby job_type :awesome, '/usr/local/bin/awesome :task :fun_level' every 2.hours do awesome "party", fun_level: "extreme" end ``` -------------------------------- ### Set Global MAILTO Environment Variable Source: https://github.com/javan/whenever/blob/main/README.md Overrides the default MAILTO environment variable for all jobs. Ensure the MAILTO variable is correctly set before defining jobs. ```ruby env 'MAILTO', 'output_of_cron@example.com' every 3.hours do command "/usr/bin/my_great_command" end ``` -------------------------------- ### Capistrano V3 Integration with Namespaced Jobs Source: https://github.com/javan/whenever/blob/main/README.md Configures Capistrano V3 to namespace crontab entries by application and stage, ensuring jobs are uniquely identified. This requires the ':application' variable to be set. ```ruby set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" } ``` -------------------------------- ### Set PATH in crontab for cron job execution Source: https://github.com/javan/whenever/wiki/Troubleshooting When cron jobs fail because the shell cannot find Ruby, include a PATH definition in your crontab file above the job schedules. This ensures that necessary executables are found. ```bash PATH=/opt/local/ree/bin:/bin:/sbin:/whateverpathyouneed ``` -------------------------------- ### Scheduled Job: Conditional on Role Source: https://github.com/javan/whenever/blob/main/README.md Schedule a job to run only on servers with a specific role, useful in deployment environments like Capistrano. ```ruby # run this task only on servers with the :app role in Capistrano # see Capistrano roles section below every :day, at: '12:20am', roles: [:app] do rake "app_server:task" end ``` -------------------------------- ### Clear Crontab Entries with `whenever --clear-crontab` Source: https://context7.com/javan/whenever/llms.txt Removes all entries associated with the current project from the system crontab. This is useful for uninstalling scheduled jobs. ```sh # Remove this project's entries from the crontab $ bundle exec whenever --clear-crontab ``` -------------------------------- ### Clear crontab to resolve execution issues Source: https://github.com/javan/whenever/wiki/Troubleshooting If commenting out .bashrc settings doesn't resolve job execution problems, try clearing the crontab. This command can sometimes resolve persistent issues. ```bash whenever --clear-crontab ``` -------------------------------- ### Comment out non-interactive shell settings in .bashrc Source: https://github.com/javan/whenever/wiki/Troubleshooting If jobs are not executing on Ubuntu with RVM, comment out the lines in ~/.bashrc that disable functionality for non-interactive shells. This ensures that cron jobs can run correctly. ```bash # If not running interactively, don't do anything [ -z "$PS1" ] && return ``` -------------------------------- ### Conditionally Set Whenever Roles in Capistrano Source: https://github.com/javan/whenever/wiki/Don't-write-crontab-in-certain-environment Use this configuration in your Capistrano deployment file to disable Whenever for the staging environment. It sets the `whenever_roles` to nil when `stage` is `:staging`, otherwise it defaults to `:db`. ```ruby set :whenever_roles, -> { stage == :staging ? nil : :db } ``` -------------------------------- ### Redirect Only Errors Source: https://github.com/javan/whenever/wiki/Output-redirection-aka-logging-your-cron-jobs Redirect only the error output of cron jobs to a specified log file. ```ruby # adds "2> error.log" to all commands set :output, {:error => 'error.log'} ``` -------------------------------- ### Restrict Jobs to Capistrano Roles Source: https://context7.com/javan/whenever/llms.txt Use the `roles:` option to restrict a job to specific Capistrano server roles. Jobs without `roles:` run on all servers in `whenever_roles`. ```ruby # config/schedule.rb # Runs on all servers in whenever_roles (default: :db) every :day, at: '12:02am' do command "run_this_everywhere" end # Only on :app servers every :day, at: '1:37pm', roles: [:app] do rake 'app:task' end # Only on :db servers every :hour, roles: [:db] do rake 'db:task' end ``` -------------------------------- ### Define script_with_lock job type Source: https://github.com/javan/whenever/wiki/Exclusive-cron-task-lock-with-flock Define a custom job type for executing scripts with a file lock. This ensures only one instance runs at a time using `flock -n`. The lock file is created in `/var/lock/`. ```ruby # usage script_with_lock 'script_name', lock: 'lock_name' job_type :script_with_lock, "cd :path && :environment_variable=:environment flock -n /var/lock/:lock.lock :bundle_command script/:task :output" ``` -------------------------------- ### Define runner_with_lock job type Source: https://github.com/javan/whenever/wiki/Exclusive-cron-task-lock-with-flock Define a custom job type for running Ruby code with a file lock. This ensures only one instance runs at a time using `flock -n`. The lock file is created in `/var/lock/`. ```ruby # usage runner_with_lock 'ruby code', lock: 'lock_name' job_type :runner_with_lock, "cd :path && flock -n /var/lock/:lock.lock :bundle_command :runner_command -e :environment ':task' :output" ``` -------------------------------- ### Generate Jobs for Specific Capistrano Roles Source: https://context7.com/javan/whenever/llms.txt Generates cron jobs only for specified Capistrano roles. This allows for role-based deployment filtering of scheduled tasks. ```sh # Generate cron jobs only for specific Capistrano roles $ bundle exec whenever --roles db,app ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.