public async Task <bool> StartAsync(CancellationToken cancellationToken, bool forceStart = false) { if (JobStatus != JobStatus.Running) { if (JobStatus == JobStatus.Stopping) { do { if (JobStatus == JobStatus.Stopped) { break; } try { Task.Delay(100, cancellationToken).Wait(cancellationToken); } catch { } if (cancellationToken.IsCancellationRequested) { break; } } while (true); } if (cancellationToken.IsCancellationRequested) { return(false); } JobStartingTask = Task.Run(() => { do { try { #if RELEASE if (!forceStart) { var scheduleNextOccurrence = DateTime.MaxValue; var now = DateTime.Now; foreach (var cronExpression in Schedules) { var schedule = NCrontab.CrontabSchedule.Parse(cronExpression); var nextOccurrence = schedule.GetNextOccurrence(now); if (nextOccurrence < scheduleNextOccurrence) { scheduleNextOccurrence = nextOccurrence; } } JobStatus = JobStatus.Scheduled; Task.Delay((int)(scheduleNextOccurrence - now).TotalMilliseconds, cancellationToken).Wait(cancellationToken); } #else if (JobStatus == JobStatus.Stopped || JobStatus == JobStatus.Stopping) { break; } #endif JobLoadCancellationTokenSource = new CancellationTokenSource(); JobUnloadCancellationTokenSource = new CancellationTokenSource(); JobStatus = JobStatus.Running; JobAssembly.Instance.StartAsync(JobLoadCancellationTokenSource.Token).Wait(JobLoadCancellationTokenSource.Token); } catch { } if (UpdatingMode) { // Stop job if already working if (JobStatus == JobStatus.Running || JobStatus == JobStatus.Paused) { JobAssembly.Instance.StopAsync(JobUnloadCancellationTokenSource.Token).Wait(JobUnloadCancellationTokenSource.Token); JobStatus = JobStatus.Stopped; } // Unload current job JobAssembly.HostAssemblyLoadContext.Unload(); // Try to load new assembly int retryWaitingTimeInMs = 2000; int retryCounter = 0; do { try { var jobAssembly = _jobLoader.Load(Path.GetDirectoryName(JobAssembly.JobFullPath)); if (jobAssembly != null) { JobAssembly = jobAssembly; break; } } catch (Exception ex) { _logger.LogError("Couldn't load the job!"); if (retryCounter <= 60) { switch (retryCounter) { case 20: retryWaitingTimeInMs = 10000; break; case 40: retryWaitingTimeInMs = 20000; break; case 60: retryWaitingTimeInMs = 60000; break; } retryCounter++; } try { Task.Delay(retryWaitingTimeInMs, cancellationToken).Wait(cancellationToken); } catch { } } } while (true); UpdatingMode = false; JobStatus = JobStatus.Scheduled; } } while (true); }); return(true); } return(false); }
public void Load(string jobPath) { var jobAssembly = _jobLoader.Load(jobPath); Register(new JobInstance(jobAssembly, _jobLoader, _logger)); }