Class: CrontabRb::Write

Inherits:
Object
  • Object
show all
Defined in:
lib/crontab_rb/write.rb

Class Method Summary collapse

Class Method Details

.combine(entries) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/crontab_rb/write.rb', line 46

def self.combine(entries)
  entries.map! { |entry| entry.split(/ +/, 6) }
  0.upto(4) do |f|
    (entries.length-1).downto(1) do |i|
      next if entries[i][f] == '*'
      comparison = entries[i][0...f] + entries[i][f+1..-1]
      (i-1).downto(0) do |j|
        next if entries[j][f] == '*'
        if comparison == entries[j][0...f] + entries[j][f+1..-1]
          entries[j][f] += ',' + entries[i][f]
          entries.delete_at(i)
          break
        end
      end
    end
  end

  entries.map { |entry| entry.join(' ') }
end

.write_crontabObject



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/crontab_rb/write.rb', line 4

def self.write_crontab
  command = 'crontab -'
  shortcut_jobs, regular_jobs = [], []
  contents = ''
  records = Database.all
  records.each do |record|
    options = {
      at: record[:at].presence,
      job_template: "/bin/bash -l -c ':job'",
      template: "cd :path && :bundle_command :runner_command -e :environment ':task' :output",
      environment_variable: 'RAILS_ENV',
      environment: 'production',
      path: Dir.pwd,
      chronic_options: {},
      runner_command: "bin/rails runner",
      bundle_command: "bundle exec",
      task: record[:command],
      mailto: ''
    }
    job = Whenever::Job.new(options)
    Whenever::Output::Cron.output(record[:time], job, chronic_options: {}) do |cron|
      cron << "\n\n"
      if cron[0,1] == "@"
        shortcut_jobs << cron
      else
        regular_jobs << cron
      end
    end
  end
  contents = shortcut_jobs.join + combine(regular_jobs).join


  IO.popen(command, 'r+') do |crontab|
    crontab.write(contents)
    crontab.close_write
  end
  success = $?.exitstatus.zero?
  if success
    puts "[write] crontab file updated"
  end
end