Module: Sinatra::ScheduleHelper

Defined in:
lib/sinatra/helpers/schedule.rb

Constant Summary collapse

@@scheduler =
Rufus::Scheduler.new

Instance Method Summary collapse

Instance Method Details

#check_file_locked?(specific_lock_file = nil) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/sinatra/helpers/schedule.rb', line 8

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

#schedule_at(cron_expression, specific_lock_file = nil) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/sinatra/helpers/schedule.rb', line 55

def schedule_at(cron_expression,specific_lock_file=nil) 
  @@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

#schedule_every(time, specific_lock_file = nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sinatra/helpers/schedule.rb', line 22

def schedule_every(time,specific_lock_file=nil) 
  @@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