How to pause/resume jobs with Quartz.Net

10.9k Views Asked by At

I have 8 jobs in my project. They start in the Application_Start event and repeat forever. Two of them are using the same class. One job every 7 seconds and the other job every 30 seconds working. But they use the same method at 1 point. Reading a date from an xml file.

If the date is older than the current date, it changes the session id and adds 20 minutes to it. The session id is constantly changing as both are trying to enter and process at the same time. The following is my need:

1 - Enter the method. 2 - If the session is to be changed, stop the tasks other than the current task. 3 - Change session and save to xml. 4 - Restart or resume all my passive tasks.

private DateTimeOffset g_canlimacgetir = DateTimeOffset.UtcNow.AddSeconds(0);
private DateTimeOffset g_canliorangetir = DateTimeOffset.UtcNow.AddSeconds(45);
private void CanliOranlariGetir()
{
    try
    {
        ISchedulerFactory schfack = new StdSchedulerFactory();
        IScheduler scheduler = schfack.GetScheduler();
        IJobDetail jobdetay = JobBuilder.Create<CanliOranlar>()
            .WithIdentity("canliorangetir")
            .Build();
        ITrigger trigger = TriggerBuilder.Create()
            .WithSimpleSchedule(s => s.WithIntervalInSeconds(7).RepeatForever()).StartAt(g_canliorangetir).Build();
        scheduler.ScheduleJob(jobdetay, trigger);
        scheduler.Start();
    }
}
private void CanliMaclariGetir()
{
    try
    {
        ISchedulerFactory schfack = new StdSchedulerFactory();
        IScheduler scheduler = schfack.GetScheduler();
        IJobDetail jobdetay = JobBuilder.Create<CanliMaclar>()
            .WithIdentity("canlimacgetir")
            .Build();
        ITrigger trigger = TriggerBuilder.Create()
            .WithSimpleSchedule(s => s.WithIntervalInSeconds(30).RepeatForever()).StartAt(g_canlimacgetir).Build();
        scheduler.ScheduleJob(jobdetay, trigger);
        scheduler.Start();
    }
}

private Headers GetTheToken()
    {
        Headers h = new Headers();
        HttpWebResponse response = null;
        try
        {
            const string session_site = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(session_site);
            Uri uri = new Uri("");

            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.ContentType = "text/html; charset=utf-8";
            request.ContentLength = 0;
            Cookie trackerID = new Cookie("trackerId", ConfigurationManager.AppSettings["TrackerID"].ToString()) { Domain = uri.Host };
            DateTime tarih = DateTime.Now;
            request.Timeout = 5000;
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.ServerCertificateValidationCallback = new
            RemoteCertificateValidationCallback(delegate { return true; });
            response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            response.Close();
            response.Dispose();
            reader.Close();
            reader.Dispose();
            DateTime sesstimeout = DateTime.Now.AddSeconds(1199);
            string getCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
            char[] ayiricilar = { '=', ',', ';' };
            string[] parcalar = getCookieHeader.Split(ayiricilar);
            int ses = 0, rv = 0, xt = 0, xct = 0;
            if (parcalar.Length > 20)
            {
                h.session_timeout = sesstimeout;
                for (int i = 0; i < parcalar.Length; i++)
                {
                    if (parcalar[i] == "ASP.NET_SessionId") { h.sessionID = parcalar[i + 1]; ses = 1; }
                    else if (parcalar[i] == "__RequestVerificationToken") { h.request_verification = parcalar[i + 1]; rv = 1; }
                    else if (parcalar[i] == "XSRF-TOKEN") { h.xsrf_token = parcalar[i + 1]; xt = 1; }
                    else if (parcalar[i] == "XSRF-COOKIE-TOKEN") { h.xsrf_cookie_token = parcalar[i + 1]; xct = 1; }
                    if (ses == 1 && rv == 1 && xt == 1 && xct == 1) i = parcalar.Length;
                }
            }
            response.Close();
            response.Dispose();

            XmlDocument doc = new XmlDocument();
            XmlReader xmlReader = new XmlTextReader(HostingEnvironment.MapPath("~/xml/values.xml"));
            doc.Load(xmlReader);
            xmlReader.Close();
            XmlNodeList InfoNode = doc.SelectNodes("SessionInfo/Info");
            InfoNode[0].Attributes["SessionExpires"].Value = h.session_timeout.ToString();
            InfoNode[0].Attributes["SessionID"].Value = h.sessionID;
            InfoNode[0].Attributes["XSRF-TOKEN"].Value = h.xsrf_token;
            InfoNode[0].Attributes["XSRF-COOKIE-TOKEN"].Value = h.xsrf_cookie_token;
            InfoNode[0].Attributes["_requestVerification"].Value = h.request_verification.ToString();
            doc.Save(HostingEnvironment.MapPath("~/xml/values.xml"));
        }
        return h;
    }
1

There are 1 best solutions below

1
On BEST ANSWER

For all jobs you can use

scheduler.PauseAll();

scheduler.ResumeAll();

But if you want to stop and start a specific job you can use this:

scheduler.PauseJob(jobdetay.Key);

scheduler.ResumeJob(jobdetay.Key);