require 'timeout' # encoding: utf-8 module Sinatra module ScheduleHelper @@scheduler = Rufus::Scheduler.new def check_file_locked?(specific_lock_file=nil) return false if specific_lock_file.nil? f = File.open("/tmp/#{specific_lock_file}", File::CREAT) Timeout::timeout(0.001) { f.flock(File::LOCK_EX) } f.flock(File::LOCK_UN) false rescue true ensure unless f.nil? f.close end end def schedule_every(time,specific_lock_file) @@scheduler.every time do unless check_file_locked?(specific_lock_file) begin file_path = specific_lock_file.nil?? "/tmp/schedule.lock" : "/tmp/#{specific_lock_file}"; 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 end def schedule_at(cron_expression,specific_lock_file) @@scheduler.cron cron_expression do unless check_file_locked?(specific_lock_file) begin file_path = specific_lock_file.nil?? "/tmp/schedule.lock" : "/tmp/#{specific_lock_file}"; 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 end register ScheduleHelper end