Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

scheduler.py 3.7 KiB

13 år sedan
13 år sedan
13 år sedan
13 år sedan
13 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
  2. # MIT License. See license.txt
  3. from __future__ import unicode_literals
  4. """
  5. Scheduler will call the following events from the module
  6. `startup.schedule_handler` and Control Panel (for server scripts)
  7. execute_always
  8. execute_daily
  9. execute_monthly
  10. execute_weekly
  11. The scheduler should be called from a cron job every x minutes (5?) depending
  12. on the need.
  13. """
  14. import webnotes
  15. import webnotes.utils
  16. def execute(site=None):
  17. """
  18. execute jobs
  19. this method triggers the other scheduler events
  20. Database connection: Ideally it should be connected from outside, if there is
  21. no connection, it will connect from defs.py
  22. """
  23. from datetime import datetime
  24. format = '%Y-%m-%d %H:%M:%S'
  25. if not webnotes.conn:
  26. webnotes.connect(site=site)
  27. out = []
  28. nowtime = webnotes.utils.now_datetime()
  29. last = webnotes.conn.get_global('scheduler_last_event')
  30. # set scheduler last event
  31. webnotes.conn.begin()
  32. webnotes.conn.set_global('scheduler_last_event', nowtime.strftime(format))
  33. webnotes.conn.commit()
  34. if last:
  35. last = datetime.strptime(last, format)
  36. if nowtime.day != last.day:
  37. # if first task of the day execute daily tasks
  38. out.append(nowtime.strftime("%Y-%m-%d %H:%M:%S") + ' - daily:' + trigger('daily'))
  39. if nowtime.month != last.month:
  40. out.append(nowtime.strftime("%Y-%m-%d %H:%M:%S") + ' - monthly:' + trigger('monthly'))
  41. if nowtime.weekday()==0:
  42. out.append(nowtime.strftime("%Y-%m-%d %H:%M:%S") + ' - weekly:' + trigger('weekly'))
  43. if nowtime.hour != last.hour:
  44. out.append(nowtime.strftime("%Y-%m-%d %H:%M:%S") + ' - hourly:' + trigger('hourly'))
  45. out.append(nowtime.strftime("%Y-%m-%d %H:%M:%S") + ' - all:' + trigger('all'))
  46. return '\n'.join(out)
  47. def trigger(method):
  48. """trigger method in startup.schedule_handler"""
  49. traceback = ""
  50. for scheduler_event in webnotes.get_hooks().scheduler_event:
  51. event_name, handler = scheduler_event.split(":")
  52. if method==event_name:
  53. try:
  54. webnotes.get_attr(handler)()
  55. webnotes.conn.commit()
  56. except Exception:
  57. traceback += log("Method: {method}, Handler: {handler}".format(method=method, handler=handler))
  58. traceback += log(webnotes.get_traceback())
  59. webnotes.conn.rollback()
  60. return traceback or 'ok'
  61. def log(method, message=None):
  62. """log error in patch_log"""
  63. message = webnotes.utils.cstr(message) + "\n" if message else ""
  64. message += webnotes.get_traceback()
  65. if not (webnotes.conn and webnotes.conn._conn):
  66. webnotes.connect()
  67. webnotes.conn.rollback()
  68. webnotes.conn.begin()
  69. d = webnotes.doc("Scheduler Log")
  70. d.method = method
  71. d.error = message
  72. d.save()
  73. webnotes.conn.commit()
  74. return message
  75. def get_errors(from_date, to_date, limit):
  76. errors = webnotes.conn.sql("""select modified, method, error from `tabScheduler Log`
  77. where date(modified) between %s and %s
  78. and error not like '%%[Errno 110] Connection timed out%%'
  79. order by modified limit %s""", (from_date, to_date, limit), as_dict=True)
  80. return ["""<p>Time: {modified}</p><pre><code>Method: {method}\n{error}</code></pre>""".format(**e)
  81. for e in errors]
  82. def get_error_report(from_date=None, to_date=None, limit=10):
  83. from webnotes.utils import get_url, now_datetime, add_days
  84. if not from_date:
  85. from_date = add_days(now_datetime().date(), -1)
  86. if not to_date:
  87. to_date = add_days(now_datetime().date(), -1)
  88. errors = get_errors(from_date, to_date, limit)
  89. if errors:
  90. return 1, """<h4>Scheduler Failed Events (max {limit}):</h4>
  91. <p>URL: <a href="{url}" target="_blank">{url}</a></p><hr>{errors}""".format(
  92. limit=limit, url=get_url(), errors="<hr>".join(errors))
  93. else:
  94. return 0, "<p>Scheduler didn't encounter any problems.</p>"
  95. if __name__=='__main__':
  96. execute()