Below you can find JobScheduler Class
using Quartz;using Quartz.Impl;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;public class JobScheduler{ public Dictionary<string, IScheduler> _schedulers; private bool _isSchedulerStarted; public JobScheduler() { _schedulers = new Dictionary<string, IScheduler>(); _isSchedulerStarted = false; } public async Task Start(string jobId, int startIndex) { try { IScheduler scheduler = await new StdSchedulerFactory().GetScheduler(); await scheduler.Start(); _isSchedulerStarted = true; if (_schedulers.ContainsKey(jobId)) { throw new ArgumentException($"A job with ID '{jobId}' already exists."); } else { IJobDetail job = JobBuilder.Create<PrintNumbersJob>() .WithIdentity(jobId, "group1") .UsingJobData("startIndex", startIndex) .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity($"{jobId}_Trigger", "group1") .StartNow() .Build(); await scheduler.ScheduleJob(job, trigger); //Console.WriteLine(scheduler); _schedulers.Add(jobId, scheduler); Console.WriteLine(_schedulers); } Console.WriteLine("Schedulers before starting job:"); foreach (var kvp in _schedulers) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); } } catch (SchedulerException ex) { Console.WriteLine($"Error starting scheduler for job ID {jobId}: {ex.Message}"); _isSchedulerStarted = false; throw; } } public bool IsSchedulerStarted() { return _isSchedulerStarted; } public async Task Stop(string jobId) { try { Console.WriteLine("Schedulers before stopping job:"); foreach (var kvp in _schedulers) { Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); } //Console.WriteLine(jobId); if (IsSchedulerStarted() ) { //_schedulers.TryGetValue(jobId, out IScheduler scheduler) IScheduler scheduler = _schedulers[jobId]; Console.WriteLine("YES"); //Console.WriteLine(scheduler); await scheduler.Shutdown(); _schedulers.Remove(jobId); Console.WriteLine($"Job with ID: {jobId} stopped successfully."); } else { throw new ArgumentException($"Job with ID: {jobId} not found."); } } catch (Exception ex) { Console.WriteLine($"Error stopping job with job ID {jobId}: {ex.Message}"); throw; } }}
Job controller looks like below
using Microsoft.AspNetCore.Mvc;using System;using System.Threading.Tasks;using trash.Models;[ApiController][Route("[controller]")] // default Job as public class JobController : ControllerBase{ private JobScheduler _jobScheduler; public JobController(JobScheduler jobScheduler) { _jobScheduler = jobScheduler; } [HttpPost("start")] public async Task<IActionResult> Start([FromBody] JobModel request) { await _jobScheduler.Start(request.JobId, 1); return Ok($"Job scheduled successfully with ID: {request.JobId}!"); } [HttpPost("stop")] public async Task<IActionResult> Stop([FromBody] JobModel request) { await _jobScheduler.Stop(request.JobId); return Ok($"Job with ID: {request.JobId} stopped successfully!"); }}
below is PrintNumberJob
using Quartz;using System;using System.Threading.Tasks;public class PrintNumbersJob : IJob{ private int _currentIndex; public Task Execute(IJobExecutionContext context) { // Retrieve starting index from job data //Console.WriteLine(context.JobDetail.Key); var dataMap = context.JobDetail.JobDataMap; _currentIndex = dataMap.GetInt("startIndex"); // Print numbers incrementally until interrupted while (true) { Console.WriteLine($"{context.JobDetail.Key} "+_currentIndex++); Task.Delay(TimeSpan.FromSeconds(10)).Wait(); } }}
Can anyone tell me where i am wrong. What i am trying to do is i want to schedule a quartz job when i hit start api with some job id, and print number starting from 1 until i hit stop api with the same job id. _schedulers dictionary has key, value pair stored when i checked in start task, but when i tried printing _schedulers in stop it shows nothing.
Also when i hit stop api with job id let say id1, it gives me error, job with job id id1 not found.
Checkout application output below to better understand
Schedulers before starting job:Key: id1, Value: Quartz.Impl.StdSchedulergroup1.id1 1group1.id1 2group1.id1 3group1.id1 4Schedulers before stopping job:Exception thrown: 'System.ArgumentException' in trash.dllError stopping job with job ID id1: Job with ID: id1 not found.