Scheduler Module 🕒
Overview
The Scheduler Module handles job scheduling and execution in the Dynamic Notification System. It is responsible for initializing the cron-based scheduler, managing scheduled jobs, and interacting with the database for job persistence.
scheduler.go 🛠️
Purpose
Manages the lifecycle of the scheduler, including initialization and shutdown.
Key Functions 🔑
Initialize
- Purpose: Sets up the scheduler and loads jobs from the database.
- Steps:
- Establishes a connection to the database using the configuration settings.
- Initializes a cron scheduler.
- Loads jobs from the database and adds them to the scheduler.
- Starts the scheduler.
- Example:
Shutdown
- Purpose: Gracefully stops the scheduler and closes the database connection.
- Steps:
- Stops the cron scheduler to prevent further job execution.
- Closes the database connection.
- Example:
job.go 📝
Purpose
Handles job-related functionalities such as loading, adding, and managing jobs.
Key Functions 🔑
GetJobSchema
- Purpose: Generates and returns a JSON schema for the
ScheduledJob
struct, aiding in API documentation or validation. - Example:
loadJobs
- Purpose: Loads jobs from the database and schedules them in the cron instance.
- Steps:
- Queries the
scheduled_jobs
table for active jobs. - Adds each job to the scheduler.
- Example:
addCronJob
- Purpose: Adds a job to the cron scheduler based on its cron expression.
- Example:
HandlePostJob
- Purpose: HTTP handler for creating a new scheduled job via a POST request.
- Example:
HandleGetJobs
- Purpose: HTTP handler for retrieving all scheduled jobs via a GET request.
- Example:
db.go 🗄️
Purpose
Handles database interactions for job scheduling.
Key Functions 🔑
loadJobsFromDB
- Purpose: Queries the
scheduled_jobs
table and returns all scheduled jobs. - Steps:
- Executes a SQL query to fetch jobs.
- Scans the result set into
ScheduledJob
structs. - Returns the jobs for further processing.
- Example:
Example Workflow 🔄
- Initialization:
- The scheduler connects to the database and loads jobs into the cron instance.
-
The cron scheduler starts executing jobs based on their defined schedule.
-
Adding Jobs:
- A new job is added via the
POST /jobs
endpoint. -
The job is inserted into the database and added to the scheduler.
-
Execution:
- The cron scheduler triggers the job's execution at the defined time.
-
Notifications are sent via the appropriate channel.
-
Shutdown:
- The scheduler stops gracefully, ensuring no running jobs are interrupted.
- Database connections are closed.
This documentation provides a detailed explanation of the Scheduler Module, enabling you to understand and extend its functionality effectively. Happy scheduling! 🎉