Guest User

Untitled

a guest
Feb 18th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. raise "Requires your OS to support forking" unless Process.respond_to? :fork
  3. require 'chronic'
  4. require 'open3'
  5.  
  6. include Open3
  7.  
  8. # Usage
  9. if ARGV.empty? or ARGV[0] == '-h' or ARGV[0] == '--help'
  10. puts <<-USAGE
  11. Usage: every [TIME INTERVAL]: [COMMAND]
  12. Where: [TIME INTERVAL] is a natural language expression of time
  13. [COMMAND] is the command you wish to run
  14.  
  15. Examples:
  16. # Delete a log file every five minutes
  17. every five minutes: rm /var/log/my_app.log
  18.  
  19. # Restart nginx every morning
  20. every day at 1AM: /etc/init.d/nginx restart
  21. USAGE
  22. exit 0
  23. end
  24.  
  25. # Validate and parse input
  26. index = ARGV.index { |arg| arg[-1] == ':' }
  27. raise "Parse error" if index.nil?
  28.  
  29. time_str = ARGV[0..index].join(' ').chomp(':').strip
  30. command_str = ARGV[index+1..-1].join(' ').strip
  31.  
  32. raise "Parse error" if command_str.nil? or command_str.empty?
  33.  
  34. run_command = Proc.new do
  35. popen3 command_str do |stdin, stdout, stderr, wait_thread|
  36. status = wait_thread.value
  37.  
  38. unless status.to_i == 0
  39. exit status.to_i
  40. end
  41. end
  42. end
  43.  
  44. transform_time_str = Proc.new do
  45. if time_str.include? 'day'
  46. time_str.sub('day', 'tomorrow')
  47. else
  48. time_str + " from now"
  49. end
  50. end
  51.  
  52.  
  53. # Fork and process
  54. if pid = fork
  55. puts "Forked with pid #{pid}"
  56. Process.detach pid
  57. exit 0
  58. else
  59. $0 = "[every #{time_str}] #{command_str}"
  60.  
  61. run_command.call
  62.  
  63. loop do
  64. next_run = Chronic.parse(transform_time_str.call)
  65. if next_run.nil?
  66. exit 1
  67. end
  68.  
  69. sleep 1 until Time.now >= next_run
  70.  
  71. run_command.call
  72. end
  73. end
Add Comment
Please, Sign In to add comment