Ping CronMissed from Ruby

On this page

Ruby's standard library has what a ping needs. This module wraps a block in the start, success and failure signals, sets open and read timeouts, and rescues its own errors so the job's result is the job's.

What should a Ruby job send?

  • A request to /start before the work, so CronMissed can time the run and notice a job that never finishes.
  • A request to the plain URL when the work succeeded, or to /fail when it did not. /<exit status> works too: 0 is a success and any other number is a failure.
  • The end of the output in the request body, up to 100,000 bytes, so the alert shows the error without a trip to the server.

What is the module?

cronmissed.rb
require "net/http"

module CronMissed
  def self.ping(url, suffix = "", body = nil)
    uri = URI("#{url}#{suffix}")
    Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 10) do |http|
      body ? http.post(uri.request_uri, body) : http.get(uri.request_uri)
    end
  rescue StandardError
    nil # a lost ping must never break the job
  end

  def self.run(url)
    ping(url, "/start")
    yield
    ping(url)
  rescue StandardError => e
    ping(url, "/fail", e.full_message.byteslice(-100_000, 100_000))
    raise
  end
end

CronMissed.run(ENV.fetch("CRONMISSED_PING_URL")) do
  # the work
end

Keep the ping URL in an environment variable or a secret store, never in a public repository: the URL is the check's only credential.

Where does this fit?

Call it from a Rake task, a whenever job or a Sidekiq worker. For whenever, a custom job type can add the curl without touching Ruby at all.

Questions and answers

Why rescue StandardError and not Exception?
StandardError covers ordinary failures. Exceptions such as Interrupt and SystemExit are meant to end the program, and the check will report the missing success ping.
Why is the request in a block?
Net::HTTP.start with a block closes the connection when the block ends, so a ping never leaves a socket open.
Create the check these snippets report to

Make a check, copy its ping URL into the snippet, and run the job once.

Start monitoring