__init__.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. """
  2. Trixy Scheduler System
  3. This module provides a comprehensive scheduling system for the Trixy application
  4. with support for multiple trigger types (including cron expressions), multiple
  5. actions, thread-safe operations, and integration with the event system.
  6. Key Features:
  7. - Multiple trigger types: date, time, event, weekday, cron expressions, intervals
  8. - Multiple action types: event triggering, ML training, function execution
  9. - Schedule persistence with file-based storage
  10. - Thread-safe operations for multi-satellite environments
  11. - Comprehensive logging and execution history
  12. - Integration with Trixy event system and application container
  13. - Standard cron syntax support (minute hour day month weekday)
  14. Components:
  15. - Scheduler: Main scheduler class for managing multiple schedules
  16. - ScheduleEntry: Individual schedule entry with triggers and actions
  17. - Triggers: Various trigger types for schedule activation
  18. - Actions: Various action types for schedule execution
  19. - CronParser: Standard cron expression parsing and validation
  20. - Persistence: Schedule storage and loading system
  21. Usage Example:
  22. from trixy_core.scheduler import Scheduler, DateTrigger, EventAction
  23. # Create scheduler
  24. scheduler = Scheduler()
  25. # Add a schedule
  26. scheduler.add_schedule(
  27. name="daily_backup",
  28. triggers=[DateTrigger(hour=2, minute=0)], # Daily at 2 AM
  29. actions=[EventAction("system_backup", {"type": "full"})],
  30. description="Daily system backup"
  31. )
  32. # Start scheduler
  33. scheduler.start()
  34. # Add cron-based schedule
  35. scheduler.add_cron_schedule(
  36. name="weekday_report",
  37. cron_expression="0 9 * * 1-5", # 9 AM on weekdays
  38. actions=[EventAction("generate_report", {"type": "daily"})]
  39. )
  40. Event Integration:
  41. The scheduler integrates with the Trixy event system by:
  42. - Triggering "schedule_triggered" events when schedules execute
  43. - Supporting EventTrigger for event-based scheduling
  44. - Using EventAction to trigger other system events
  45. - Providing execution history through event system
  46. Cron Expression Support:
  47. Standard cron syntax with 5 fields:
  48. - Minute (0-59)
  49. - Hour (0-23)
  50. - Day of month (1-31)
  51. - Month (1-12)
  52. - Day of week (0-7, where 0 and 7 = Sunday)
  53. Examples:
  54. - "0 9 * * 1-5" = 9 AM on weekdays
  55. - "*/15 * * * *" = Every 15 minutes
  56. - "0 0 1 * *" = First day of every month at midnight
  57. - "30 14 * * 0" = 2:30 PM every Sunday
  58. """
  59. from .schedule_entry import (
  60. ScheduleEntry,
  61. ScheduleStatus,
  62. ExecutionResult,
  63. ExecutionHistory,
  64. ScheduleEntryError,
  65. NameConflictError,
  66. ValidationError,
  67. ExecutionError,
  68. get_registered_names,
  69. is_name_available,
  70. clear_name_registry
  71. )
  72. from .triggers import (
  73. # Base classes
  74. BaseTrigger,
  75. TriggerError,
  76. TriggerValidationError,
  77. # Trigger implementations
  78. DateTrigger,
  79. TimeTrigger,
  80. EventTrigger,
  81. WeekdayTrigger,
  82. CronTrigger,
  83. IntervalTrigger,
  84. ManualTrigger,
  85. # Trigger factory
  86. TriggerFactory,
  87. create_trigger_from_dict,
  88. # Utility functions
  89. get_supported_trigger_types,
  90. validate_trigger_config
  91. )
  92. from .actions import (
  93. # Base classes
  94. BaseAction,
  95. ActionError,
  96. ActionValidationError,
  97. ActionExecutionError,
  98. # Action implementations
  99. EventAction,
  100. MLTrainingAction,
  101. FunctionAction,
  102. MultiAction,
  103. ConditionalAction,
  104. # Action factory
  105. ActionFactory,
  106. create_action_from_dict,
  107. # Utility functions
  108. get_supported_action_types,
  109. validate_action_config
  110. )
  111. from .cron_parser import (
  112. CronParser,
  113. CronExpression,
  114. CronField,
  115. CronParseError,
  116. CronValidationError,
  117. parse_cron_expression,
  118. validate_cron_expression,
  119. get_next_cron_time,
  120. cron_matches_time
  121. )
  122. from .persistence import (
  123. SchedulePersistence,
  124. PersistenceError,
  125. ScheduleStorage,
  126. load_schedules_from_file,
  127. save_schedules_to_file,
  128. create_backup,
  129. restore_from_backup
  130. )
  131. from .scheduler import (
  132. Scheduler,
  133. SchedulerError,
  134. SchedulerStatus,
  135. ScheduleManager,
  136. ScheduleQuery,
  137. SchedulerConfig
  138. )
  139. # Version information
  140. __version__ = "1.0.0"
  141. __author__ = "Trixy Development Team"
  142. # Public API
  143. __all__ = [
  144. # Main scheduler class
  145. "Scheduler",
  146. "SchedulerError",
  147. "SchedulerStatus",
  148. "ScheduleManager",
  149. "ScheduleQuery",
  150. "SchedulerConfig",
  151. # Schedule entries
  152. "ScheduleEntry",
  153. "ScheduleStatus",
  154. "ExecutionResult",
  155. "ExecutionHistory",
  156. "ScheduleEntryError",
  157. "NameConflictError",
  158. "ValidationError",
  159. "ExecutionError",
  160. # Triggers
  161. "BaseTrigger",
  162. "TriggerError",
  163. "TriggerValidationError",
  164. "DateTrigger",
  165. "TimeTrigger",
  166. "EventTrigger",
  167. "WeekdayTrigger",
  168. "CronTrigger",
  169. "IntervalTrigger",
  170. "ManualTrigger",
  171. "TriggerFactory",
  172. # Actions
  173. "BaseAction",
  174. "ActionError",
  175. "ActionValidationError",
  176. "ActionExecutionError",
  177. "EventAction",
  178. "MLTrainingAction",
  179. "FunctionAction",
  180. "MultiAction",
  181. "ConditionalAction",
  182. "ActionFactory",
  183. # Cron parsing
  184. "CronParser",
  185. "CronExpression",
  186. "CronField",
  187. "CronParseError",
  188. "CronValidationError",
  189. "parse_cron_expression",
  190. "validate_cron_expression",
  191. "get_next_cron_time",
  192. "cron_matches_time",
  193. # Persistence
  194. "SchedulePersistence",
  195. "PersistenceError",
  196. "ScheduleStorage",
  197. "load_schedules_from_file",
  198. "save_schedules_to_file",
  199. "create_backup",
  200. "restore_from_backup",
  201. # Utility functions
  202. "get_registered_names",
  203. "is_name_available",
  204. "clear_name_registry",
  205. "create_trigger_from_dict",
  206. "create_action_from_dict",
  207. "get_supported_trigger_types",
  208. "get_supported_action_types",
  209. "validate_trigger_config",
  210. "validate_action_config"
  211. ]
  212. def pprint(message: str) -> None:
  213. """
  214. Scheduler module logging function that adapts based on mode.
  215. Uses the same pattern as specified in CLAUDE.md.
  216. """
  217. print(f"[SCHEDULER] {message}")
  218. def create_default_scheduler(**kwargs) -> Scheduler:
  219. """
  220. Create a default Scheduler instance with reasonable defaults.
  221. Args:
  222. **kwargs: Additional arguments to pass to Scheduler constructor
  223. Returns:
  224. Scheduler: Configured scheduler instance
  225. """
  226. return Scheduler(**kwargs)
  227. def create_simple_schedule(
  228. name: str,
  229. cron_expression: str,
  230. event_name: str,
  231. event_data: dict = None,
  232. description: str = "",
  233. **kwargs
  234. ) -> ScheduleEntry:
  235. """
  236. Create a simple schedule with cron trigger and event action.
  237. Args:
  238. name: Unique name for the schedule
  239. cron_expression: Standard cron expression (e.g., "0 9 * * 1-5")
  240. event_name: Name of event to trigger
  241. event_data: Optional data to pass with event
  242. description: Schedule description
  243. **kwargs: Additional ScheduleEntry parameters
  244. Returns:
  245. ScheduleEntry: Configured schedule entry
  246. Example:
  247. # Create daily backup at 2 AM
  248. schedule = create_simple_schedule(
  249. name="daily_backup",
  250. cron_expression="0 2 * * *",
  251. event_name="system_backup",
  252. event_data={"type": "full"},
  253. description="Daily system backup"
  254. )
  255. """
  256. schedule = ScheduleEntry(name=name, description=description, **kwargs)
  257. schedule.add_trigger(CronTrigger(cron_expression))
  258. schedule.add_action(EventAction(event_name, event_data or {}))
  259. return schedule
  260. def get_scheduler_info() -> dict:
  261. """
  262. Get information about the scheduler system.
  263. Returns:
  264. dict: Information about supported features and capabilities
  265. """
  266. return {
  267. "version": __version__,
  268. "author": __author__,
  269. "supported_triggers": get_supported_trigger_types(),
  270. "supported_actions": get_supported_action_types(),
  271. "cron_support": True,
  272. "event_integration": True,
  273. "persistence": True,
  274. "thread_safe": True,
  275. "features": [
  276. "Multiple triggers per schedule",
  277. "Multiple actions per schedule",
  278. "Standard cron expression support",
  279. "Event-based triggers and actions",
  280. "ML training integration",
  281. "Function execution actions",
  282. "Schedule persistence to file",
  283. "Execution history tracking",
  284. "Thread-safe operations",
  285. "Name uniqueness validation",
  286. "Comprehensive error handling",
  287. "Integration with Trixy event system"
  288. ]
  289. }
  290. # Initialize logging for the scheduler module
  291. pprint(f"Trixy Scheduler System v{__version__} initialized")