__main__.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. """Main app"""
  2. from datetime import datetime, timedelta
  3. import random
  4. import time
  5. from app import scheduler, LOGGER
  6. from app.api import download_resources, refill
  7. from app.database import save_resources
  8. from app.app import need_refill, max_refill_seconds, print_resources
  9. def job_check_resources(state_id, capital_id, resource_id, do_refill):
  10. """Check resources and refill if necessary"""
  11. regions = download_resources(state_id, resource_id)
  12. print_resources(regions)
  13. save_resources(state_id, regions, resource_id)
  14. if do_refill and need_refill(regions, 25):
  15. max_seconds = max_refill_seconds(regions, 25, 900)
  16. random_seconds = random.randint(0, max_seconds)
  17. random_time_delta = timedelta(seconds=random_seconds)
  18. scheduled_date = datetime.now() + random_time_delta
  19. job_id = 'refill_{}_{}'.format(capital_id, resource_id)
  20. LOGGER.info(
  21. 'Refil resource %s at %s (%s minutes)',
  22. resource_id,
  23. scheduled_date,
  24. round(random_time_delta.seconds / 60)
  25. )
  26. job = scheduler.get_job(job_id)
  27. if not job:
  28. scheduler.add_job(
  29. job_refill_resource,
  30. 'date',
  31. args=[state_id, capital_id, resource_id],
  32. id=job_id,
  33. run_date=scheduled_date
  34. )
  35. def job_refill_resource(state_id, capital_id, resource_id):
  36. """Execute refill job"""
  37. refill(state_id, capital_id, resource_id)
  38. def add_check_resources(state_id, capital_id, resource_id, do_refill, minute):
  39. """Add check resources job"""
  40. scheduler.add_job(
  41. job_check_resources,
  42. 'cron',
  43. args=[state_id, capital_id, resource_id, do_refill],
  44. id='{}_check_{}'.format(state_id, resource_id),
  45. replace_existing=True,
  46. minute=minute
  47. )
  48. if __name__ == '__main__':
  49. # job_refill_resource(2788, 4002, 0)
  50. # job_check_resources(2788, 4002, 0, False) # VN
  51. # job_check_resources(2620, 4002, 0, False) # Zeelandiae
  52. # VN
  53. add_check_resources(2788, 4008, 0, True, '0,15,30,45')
  54. add_check_resources(2788, 4008, 11, True, '0')
  55. # Zeelandiae
  56. add_check_resources(2620, 0, 0, False, '50')
  57. # Belgium
  58. add_check_resources(2604, 0, 0, False, '40')
  59. try:
  60. while True:
  61. time.sleep(100)
  62. except KeyboardInterrupt:
  63. LOGGER.info('Exiting application')
  64. SCHEDULER.shutdown()
  65. exit()