job.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. # Copyright (C) 2012-2014 Zammad Foundation, http://zammad-foundation.org/
  2. class Job < ApplicationModel
  3. store :timeplan
  4. store :condition
  5. store :execute
  6. validates :name, presence: true
  7. before_create :updated_matching
  8. before_update :updated_matching
  9. notify_clients_support
  10. def self.run
  11. time = Time.zone.now
  12. day_map = {
  13. 0 => 'sun',
  14. 1 => 'mon',
  15. 2 => 'tue',
  16. 3 => 'wed',
  17. 4 => 'thu',
  18. 5 => 'fri',
  19. 6 => 'sat',
  20. }
  21. jobs = Job.where( active: true )
  22. jobs.each do |job|
  23. # only execute jobs, older then 1 min, to give admin posibility to change
  24. next if job.updated_at > Time.zone.now - 1.minute
  25. # check if jobs need to be executed
  26. # ignore if job was running within last 10 min.
  27. next if job.last_run_at && job.last_run_at > Time.zone.now - 10.minutes
  28. # check day
  29. next if !job.timeplan['days'].include?( day_map[time.wday] )
  30. # check hour
  31. next if !job.timeplan['hours'].include?( time.hour.to_s )
  32. # check min
  33. next if !job.timeplan['minutes'].include?( match_minutes(time.min.to_s) )
  34. # find tickets to change
  35. tickets = Ticket.where( job.condition.permit! )
  36. .order( '`tickets`.`created_at` DESC' )
  37. .limit( 1_000 )
  38. job.processed = tickets.count
  39. tickets.each do |ticket|
  40. logger.debug "CHANGE #{job.execute.inspect}"
  41. changed = false
  42. job.execute.each do |key, value|
  43. changed = true
  44. attribute = key.split('.', 2).last
  45. logger.debug "-- #{Ticket.columns_hash[ attribute ].type}"
  46. #value = 4
  47. #if Ticket.columns_hash[ attribute ].type == :integer
  48. # logger.debug "to i #{attribute}/#{value.inspect}/#{value.to_i.inspect}"
  49. # #value = value.to_i
  50. #end
  51. ticket[attribute] = value
  52. logger.debug "set #{attribute} = #{value.inspect}"
  53. end
  54. next if !changed
  55. ticket.updated_by_id = 1
  56. ticket.save
  57. end
  58. job.last_run_at = Time.zone.now
  59. job.save
  60. end
  61. true
  62. end
  63. private
  64. def updated_matching
  65. count = Ticket.where( condition.permit! ).count
  66. self.matching = count
  67. end
  68. def self.match_minutes(minutes)
  69. minutes.gsub!(/(\d)\d/, '\\1')
  70. minutes.to_s + '0'
  71. end
  72. private_class_method :match_minutes
  73. end