require 'timeout' # encoding: utf-8 module Sinatra module ScheduleHelper @@scheduler = Rufus::Scheduler.new def schedule_every(time) @@scheduler.every time do begin file_path = "/tmp/schedule.lock"; f = File.open(file_path, "w+") # if file was previosly locked then flock throw a exception f.flock(File::LOCK_EX) ten_minutes = 600 # if the process overcome ten minutes, the timeout api throw a exception Timeout::timeout(ten_minutes) do begin yield rescue StandardError => error title = error.message.split(':')[0].gsub('#<',''); message = error.backtrace.join(','); NotificationSender.instance.send_error(nil,title,message) end end ensure unless f.nil? f.flock(File::LOCK_UN) f.close end end end end def schedule_at(cron_expression) @@scheduler.cron cron_expression do begin file_path = "/tmp/schedule.lock"; f = File.open(file_path, "w+") # if file was previosly locked then flock throw a exception f.flock(File::LOCK_EX) ten_minutes = 600 # if the process overcome ten minutes, the timeout api throw a exception Timeout::timeout(ten_minutes) do begin yield rescue error title = error.message.split(':')[0].gsub('#<',''); message = error.backtrace.join(','); NotificationSender.instance.send_error(nil,title,message) end end ensure unless f.nil? f.flock(File::LOCK_UN) f.close end end end end end register ScheduleHelper end