|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import threading |
| 4 | +import urllib.error |
| 5 | +import urllib.request |
| 6 | +from datetime import datetime, timedelta |
| 7 | +from pathlib import Path |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class DailyFileDownloadJob: |
| 13 | + def __init__(self, url, local_path, run_time="09:00"): |
| 14 | + """ |
| 15 | + Initialize a daily file download job. |
| 16 | +
|
| 17 | + Args: |
| 18 | + url: URL to download the file from |
| 19 | + local_path: Local path to save the file |
| 20 | + run_time: Time to run daily download in "HH:MM" format (24-hour) |
| 21 | + """ |
| 22 | + self.url = url |
| 23 | + self.local_path: Path = Path(local_path) |
| 24 | + self.local_path.parent.mkdir(parents=True, exist_ok=True) |
| 25 | + self.run_time = self._parse_run_time(run_time) |
| 26 | + self.stop_event = threading.Event() |
| 27 | + self.thread = None |
| 28 | + |
| 29 | + def _parse_run_time(self, run_time_str): |
| 30 | + """Parse run time string to hours and minutes.""" |
| 31 | + try: |
| 32 | + hour, minute = map(int, run_time_str.split(':')) |
| 33 | + if not (0 <= hour <= 23 and 0 <= minute <= 59): |
| 34 | + raise ValueError("Invalid time range") |
| 35 | + return hour, minute |
| 36 | + except (ValueError, AttributeError): |
| 37 | + logger.error(f"Invalid run_time format: {run_time_str}. Must be in 'HH:MM' format") |
| 38 | + raise ValueError("run_time must be in 'HH:MM' format") |
| 39 | + |
| 40 | + def _get_next_run_time(self): |
| 41 | + """Calculate the next run time based on the current time.""" |
| 42 | + now = datetime.now() |
| 43 | + run_hour, run_minute = self.run_time |
| 44 | + next_run = now.replace(hour=run_hour, minute=run_minute, second=0, microsecond=0) |
| 45 | + |
| 46 | + # If today's run time has passed, schedule for tomorrow |
| 47 | + if next_run <= now: |
| 48 | + next_run += timedelta(days=1) |
| 49 | + |
| 50 | + return next_run |
| 51 | + |
| 52 | + def _file_needs_update(self): |
| 53 | + """Check if the file needs to be downloaded (doesn't exist or is older than a day).""" |
| 54 | + try: |
| 55 | + file_mod_time = datetime.fromtimestamp(os.path.getmtime(self.local_path)) |
| 56 | + one_day_ago = datetime.now() - timedelta(days=1) |
| 57 | + needs_update = file_mod_time < one_day_ago |
| 58 | + if needs_update: |
| 59 | + logger.info(f"File {self.local_path} is older than 24 hours, needs update") |
| 60 | + else: |
| 61 | + logger.debug(f"File {self.local_path} is up to date") |
| 62 | + return needs_update |
| 63 | + except OSError as e: |
| 64 | + logger.warning(f"Could not get file modification time for {self.local_path}: {e}") |
| 65 | + # If we can't get file info, assume it needs to be updated |
| 66 | + return True |
| 67 | + |
| 68 | + def _download_file(self): |
| 69 | + """Download the file from URL to the local path.""" |
| 70 | + try: |
| 71 | + logger.info(f"Starting download from {self.url} to {self.local_path}") |
| 72 | + urllib.request.urlretrieve(self.url, self.local_path) |
| 73 | + logger.info(f"Download completed successfully to {self.local_path}") |
| 74 | + return True |
| 75 | + except urllib.error.URLError as e: |
| 76 | + logger.error(f"Network error during download from {self.url}: {e}") |
| 77 | + return False |
| 78 | + except Exception as e: |
| 79 | + logger.error(f"Unexpected error during download from {self.url}: {e}") |
| 80 | + return False |
| 81 | + |
| 82 | + def _run_immediate_download_if_needed(self): |
| 83 | + """Check and perform immediate download if the file needs update.""" |
| 84 | + if self._file_needs_update(): |
| 85 | + logger.info("Performing immediate download due to outdated or missing file") |
| 86 | + return self._download_file() |
| 87 | + return True |
| 88 | + |
| 89 | + def _run_loop(self): |
| 90 | + """Main execution loop.""" |
| 91 | + logger.info("Daily file download job started") |
| 92 | + |
| 93 | + # First, check if the immediate download is needed |
| 94 | + self._run_immediate_download_if_needed() |
| 95 | + |
| 96 | + while not self.stop_event.is_set(): |
| 97 | + next_run = self._get_next_run_time() |
| 98 | + sleep_time = (next_run - datetime.now()).total_seconds() |
| 99 | + |
| 100 | + logger.info(f"Next scheduled download: {next_run}") |
| 101 | + |
| 102 | + # Wait until the next run time or the stop event |
| 103 | + if self.stop_event.wait(timeout=sleep_time): |
| 104 | + logger.info("Stop event received, exiting download loop") |
| 105 | + break |
| 106 | + |
| 107 | + # Execute daily download if not stopping |
| 108 | + if not self.stop_event.is_set(): |
| 109 | + self._download_file() |
| 110 | + |
| 111 | + def start(self): |
| 112 | + """Start the daily download job in a background thread.""" |
| 113 | + if self.thread is not None and self.thread.is_alive(): |
| 114 | + logger.warning("Download job is already running") |
| 115 | + return |
| 116 | + |
| 117 | + self.stop_event.clear() |
| 118 | + self.thread = threading.Thread(target=self._run_loop, daemon=False) |
| 119 | + self.thread.start() |
| 120 | + logger.info(f"Daily file download job started for {self.url}") |
| 121 | + |
| 122 | + def stop(self, timeout=30): |
| 123 | + """ |
| 124 | + Stop the download job gracefully. |
| 125 | +
|
| 126 | + Args: |
| 127 | + timeout: Maximum time to wait for graceful shutdown (seconds) |
| 128 | + """ |
| 129 | + if self.thread is None or not self.thread.is_alive(): |
| 130 | + logger.debug("Download job is not running") |
| 131 | + return True |
| 132 | + |
| 133 | + logger.info("Stopping daily download job...") |
| 134 | + self.stop_event.set() |
| 135 | + |
| 136 | + # Wait for the thread to finish gracefully |
| 137 | + self.thread.join(timeout=timeout) |
| 138 | + |
| 139 | + if self.thread.is_alive(): |
| 140 | + logger.warning("Download job did not stop gracefully within timeout") |
| 141 | + return False |
| 142 | + else: |
| 143 | + logger.info("Daily download job stopped successfully") |
| 144 | + return True |
0 commit comments