public override void SetUp() { base.SetUp(); mockJobStore = Mocks.CreateMock<IJobStore>(); mockJobRunner = Mocks.CreateMock<IJobRunner>(); mockLogger = Mocks.CreateMock<ILogger>(); mockTrigger = Mocks.PartialMock<Trigger>(); scheduler = new DefaultScheduler(mockJobStore, mockJobRunner); dummyJobData = new JobData(); dummyJobSpec = new JobSpec("foo", "bar", "key", mockTrigger); dummyJobDetails = new JobDetails(dummyJobSpec, DateTime.UtcNow); isWoken = false; // Ensure the scheduler is initialized. mockJobStore.RegisterScheduler(scheduler.Guid, scheduler.Name); Mocks.Replay(mockJobStore); scheduler.Initialize(); Mocks.Verify(mockJobStore); Mocks.BackToRecord(mockJobStore); mockJobStore.UnregisterScheduler(scheduler.Guid); // Create a separate uninitialized scheduler for certain tests. uninitializedScheduler = new DefaultScheduler(mockJobStore, mockJobRunner); }
public void Name_GetterAndSetter() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.Name = "new name"; Assert.AreEqual("new name", spec.Name); }
public void ConstructorSetsProperties() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); Assert.AreEqual("abc", spec.Name); Assert.AreEqual("some job", spec.Description); Assert.AreEqual("with this key", spec.JobKey); Assert.AreSame(trigger, spec.Trigger); Assert.IsNull(spec.JobData); }
public override void SetUp() { base.SetUp(); scheduler = Mocks.CreateMock<IScheduler>(); logger = Mocks.CreateMock<ILogger>(); jobSpec = new JobSpec("abc", "some job", "with.this.key", PeriodicTrigger.CreateDailyTrigger(DateTime.UtcNow)); jobData = new JobData(); Mocks.ReplayAll(); }
public override void SetUp() { base.SetUp(); dummyJobSpec = new JobSpec("job", "test", "dummy", PeriodicTrigger.CreateOneShotTrigger(DateTime.UtcNow)); dummyJobData = new JobData(); dummyJobData.State["key"] = "value"; jobStore = CreateJobStore(); jobStore.RegisterScheduler(SchedulerGuid, SchedulerName); }
/// <summary> /// Creates a job execution context. /// </summary> /// <param name="scheduler">The scheduler that is managing the job</param> /// <param name="logger">The logger to use for logging job progress</param> /// <param name="jobSpec">The job's specification</param> /// <param name="jobData">The job state data, or null if none</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="scheduler"/>, /// <paramref name="logger"/> or <paramref name="jobSpec"/> is null</exception> public JobExecutionContext(IScheduler scheduler, ILogger logger, JobSpec jobSpec, JobData jobData) { if (scheduler == null) throw new ArgumentNullException("scheduler"); if (logger == null) throw new ArgumentNullException("logger"); if (jobSpec == null) throw new ArgumentNullException("jobSpec"); this.scheduler = scheduler; this.logger = logger; this.jobSpec = jobSpec; this.jobData = jobData; }
public static void AreEqual(JobSpec expected, JobSpec actual) { if (expected == null) { Assert.IsNull(actual); return; } Assert.IsNotNull(actual); Assert.AreEqual(expected.Name, actual.Name); Assert.AreEqual(expected.Description, actual.Description); Assert.AreEqual(expected.JobKey, actual.JobKey); AreEqual(expected.Trigger, actual.Trigger); AreEqual(expected.JobData, actual.JobData); }
public void ClonePerformsADeepCopy(bool useGenericClonable, bool jobDataIsNull) { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.JobData = jobDataIsNull ? null : new JobData(); JobSpec clone = useGenericClonable ? spec.Clone() : (JobSpec) ((ICloneable) spec).Clone(); Assert.AreNotSame(spec, clone); Assert.AreNotSame(trigger, clone.Trigger); if (! jobDataIsNull) Assert.AreNotSame(spec.JobData, clone.JobData); JobAssert.AreEqual(spec, clone); }
/// <inheritdoc /> public override bool CreateJob(JobSpec jobSpec, DateTime creationTimeUtc, CreateJobConflictAction conflictAction) { if (jobSpec == null) { throw new ArgumentNullException("jobSpec"); } if (!Enum.IsDefined(typeof(CreateJobConflictAction), conflictAction)) { throw new ArgumentOutOfRangeException("conflictAction"); } lock (jobs) { ThrowIfDisposed(); VersionedJobDetails existingJobDetails; if (jobs.TryGetValue(jobSpec.Name, out existingJobDetails)) { switch (conflictAction) { case CreateJobConflictAction.Ignore: return(false); case CreateJobConflictAction.Update: InternalUpdateJob(existingJobDetails, jobSpec); return(true); case CreateJobConflictAction.Replace: break; case CreateJobConflictAction.Throw: throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "There is already a job with name '{0}'.", jobSpec.Name)); } } VersionedJobDetails jobDetails = new VersionedJobDetails(jobSpec.Clone(), creationTimeUtc, 0); jobs[jobSpec.Name] = jobDetails; Monitor.PulseAll(jobs); return(true); } }
/// <inheritdoc /> public override void UpdateJob(string existingJobName, JobSpec updatedJobSpec) { if (existingJobName == null) { throw new ArgumentNullException("existingJobName"); } if (existingJobName.Length == 0) { throw new ArgumentException("existingJobName"); } if (updatedJobSpec == null) { throw new ArgumentNullException("jobSpec"); } ThrowIfDisposed(); jobStoreDao.UpdateJob(clusterName, existingJobName, updatedJobSpec); }
/// <summary> /// Registers the given jobType. /// </summary> /// <param name="jobName"> /// The name to use when registering the job. /// </param> /// <param name="jobType"> /// The Type of to class to register which implements IJob. /// </param> public void RegisterJobType(string jobName, Type jobType) { if (String.IsNullOrWhiteSpace(jobName)) { throw new ArgumentNullException("jobName"); } else if (null == jobType) { throw new ArgumentNullException("jobType"); } else if (jobType.GetInterface("IJob") != typeof(IJob)) { throw new ArgumentException("The jobType must implement the IJob interface."); } JobSpec spec = new JobSpec(jobType, jobName); nameToSpecMap[jobName] = spec; typeToSpecMap[jobType] = spec; }
public void ClonePerformsADeepCopy(bool useGenericClonable, bool jobDataIsNull) { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.JobData = jobDataIsNull ? null : new JobData(); JobSpec clone = useGenericClonable ? spec.Clone() : (JobSpec)((ICloneable)spec).Clone(); Assert.AreNotSame(spec, clone); Assert.AreNotSame(trigger, clone.Trigger); if (!jobDataIsNull) { Assert.AreNotSame(spec.JobData, clone.JobData); } JobAssert.AreEqual(spec, clone); }
/// <inheritdoc /> public override bool CreateJob(JobSpec jobSpec, DateTime creationTimeUtc, CreateJobConflictAction conflictAction) { if (jobSpec == null) throw new ArgumentNullException("jobSpec"); if (!Enum.IsDefined(typeof (CreateJobConflictAction), conflictAction)) throw new ArgumentOutOfRangeException("conflictAction"); lock (jobs) { ThrowIfDisposed(); VersionedJobDetails existingJobDetails; if (jobs.TryGetValue(jobSpec.Name, out existingJobDetails)) { switch (conflictAction) { case CreateJobConflictAction.Ignore: return false; case CreateJobConflictAction.Update: InternalUpdateJob(existingJobDetails, jobSpec); return true; case CreateJobConflictAction.Replace: break; case CreateJobConflictAction.Throw: throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "There is already a job with name '{0}'.", jobSpec.Name)); } } VersionedJobDetails jobDetails = new VersionedJobDetails(jobSpec.Clone(), creationTimeUtc, 0); jobs[jobSpec.Name] = jobDetails; Monitor.PulseAll(jobs); return true; } }
public void UpdateJob_CanRenameJobsAndAlterOtherProperties() { Mocks.ReplayAll(); JobDetails originalJob = CreateRunningJob("originalJob"); JobSpec updatedJobSpec = new JobSpec("updatedJob", "This is updated.", "The new key", PeriodicTrigger.CreateOneShotTrigger(new DateTime(2000, 3, 4))); jobStore.UpdateJob("originalJob", updatedJobSpec); Assert.IsNull(jobStore.GetJobDetails("originalJob"), "The job should not be accessible under its original name."); // The job gets a new job spec, but all other properties should be preserved including // the job's execution history. JobDetails updatedJob = jobStore.GetJobDetails("updatedJob"); JobDetails expectedUpdatedJob = originalJob.Clone(); expectedUpdatedJob.JobSpec = updatedJobSpec; JobAssert.AreEqual(expectedUpdatedJob, updatedJob); }
private void QueueJob(IMongoCollection <JobSpec <string> > jobsCollection, JobSpec <string> job) { var filterCondition = Builders <JobSpec <string> > .Filter.Eq(j => j.Uuid, job.Uuid); var updateCondition = Builders <JobSpec <string> > .Update.Set(j => j.Status, JobStatuses.Queued); jobsCollection.UpdateOne(filterCondition, updateCondition); try { this.channel.BasicPublish( exchange: string.Empty, routingKey: "jobs", basicProperties: null, body: Guid.Parse(job.Uuid).ToByteArray()); } catch (Exception) { // TODO: Figure out what exception to use here. updateCondition = Builders <JobSpec <string> > .Update.Set(j => j.Status, JobStatuses.New); jobsCollection.UpdateOne(filterCondition, updateCondition); } }
public void Trigger_ThrowsIfValueIsNull() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.Trigger = null; }
/// <inheritdoc /> public abstract void UpdateJob(string existingJobName, JobSpec updatedJobSpec);
public void Description_GetterAndSetter() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.Description = "new description"; Assert.AreEqual("new description", spec.Description); }
public void JobKey_GetterAndSetter() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.JobKey = "new key"; Assert.AreEqual("new key", spec.JobKey); }
/// <inheritdoc /> public override bool CreateJob(JobSpec jobSpec, DateTime creationTimeUtc, CreateJobConflictAction conflictAction) { if (jobSpec == null) throw new ArgumentNullException("jobSpec"); if (!Enum.IsDefined(typeof (CreateJobConflictAction), conflictAction)) throw new ArgumentOutOfRangeException("conflictAction"); ThrowIfDisposed(); return jobStoreDao.CreateJob(clusterName, jobSpec, creationTimeUtc, conflictAction); }
/// <summary> /// Updates an existing job. /// </summary> /// <param name="clusterName">The cluster name, never null</param> /// <param name="existingJobName">The name of the existing job to update</param> /// <param name="updatedJobSpec">The updated job specification</param> /// <exception cref="SchedulerException">Thrown if an error occurs or if the job does not exist</exception> public virtual void UpdateJob(string clusterName, string existingJobName, JobSpec updatedJobSpec) { try { using (IDbConnection connection = CreateConnection()) { IDbCommand command = CreateStoredProcedureCommand(connection, "spSCHED_UpdateJob"); AddInputParameter(command, "ClusterName", DbType.String, clusterName); AddInputParameter(command, "ExistingJobName", DbType.String, existingJobName); AddInputParameter(command, "UpdatedJobName", DbType.String, updatedJobSpec.Name); AddInputParameter(command, "UpdatedJobDescription", DbType.String, updatedJobSpec.Description); AddInputParameter(command, "UpdatedJobKey", DbType.String, updatedJobSpec.JobKey); AddInputParameter(command, "UpdatedTriggerObject", DbType.Binary, DbUtils.MapObjectToDbValue(DbUtils.SerializeObject(updatedJobSpec.Trigger))); AddInputParameter(command, "UpdatedJobDataObject", DbType.Binary, DbUtils.MapObjectToDbValue(DbUtils.SerializeObject(updatedJobSpec.JobData))); IDbDataParameter resultCodeParam = AddOutputParameter(command, "ResultCode", DbType.Int32); connection.Open(); command.ExecuteNonQuery(); UpdateJobResultCode resultCode = (UpdateJobResultCode) resultCodeParam.Value; switch (resultCode) { case UpdateJobResultCode.JobUpdated: return; case UpdateJobResultCode.ExistingJobNotFound: throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "Job '{0}' does not exist so it cannot be updated.", existingJobName)); case UpdateJobResultCode.JobWithUpdatedNameExists: throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "Cannot rename job '{0}' to '{1}' because there already exists another job with the new name.", existingJobName, updatedJobSpec.Name)); default: throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "spSCHED_UpdateJob returned unrecognized result code '{0}'.", resultCode)); } } } catch (Exception ex) { throw new SchedulerException("The job store was unable to update a job in the database.", ex); } }
public void Name_ThrowsIfValueIsEmpty() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.Name = ""; }
/// <inheritdoc /> public abstract bool CreateJob(JobSpec jobSpec, DateTime creationTimeUtc, CreateJobConflictAction conflictAction);
public IList<RisultatoInvioMessaggio> InvioMessaggio(int idAzienda, PersonaMessaggioDTO personaMessaggioDTO, Condominio condominio, int? idUnitaImmobiliare, int? idFornitore, int? idResponsabile, int? idIncaricatoAttivita, MotivoMessaggio motivoMessaggio, string oggetto, string testo, IList<string> destinatari, string mittente, string emailRapportino, IList<DocumentInfo> allegati, ParametriInvioLettera parametriInvioLettera) { // ========================================================= // Disabilito l'invio asincrono per problemi di gestione con Sertea // diversi messaggi non sono stati inviati bugid#3823 // ========================================================= parametriInvioLettera.Asincrono = false; var message = string.Empty; var invioRiuscito = false; Persona persona = null; if(personaMessaggioDTO != null) persona = _daoFactory.GetPersonaDao().Find(personaMessaggioDTO.ID, false); _persona = persona; _condominio = condominio; _motivoMessaggio = motivoMessaggio; _oggetto = oggetto; _testo = testo; _destinatari = destinatari; _mittente = mittente; _emailRapportino = emailRapportino; var results = new List<RisultatoInvioMessaggio>(); var result = new eMessageResultSendSMS(); try { var destinatariSend = new List<string>(); if (destinatari.Count > 0 && !destinatari.All(string.IsNullOrEmpty)) { foreach (var item in destinatari) { if (!string.IsNullOrEmpty(item)) { if (!item.Trim().StartsWith("+39")) destinatariSend.Add("+39" + Library.Conversione.ToPhoneNumber(item)); else destinatariSend.Add(Library.Conversione.ToPhoneNumber(item)); } } if (destinatariSend.Any()) { // ===================================== // Applico la stampa unione // ===================================== if (personaMessaggioDTO != null) { int? idCondominio = null; if (condominio != null) idCondominio = condominio.ID; var parametri = new ParametriStampaUnione(persona.ID, idUnitaImmobiliare, idResponsabile, idIncaricatoAttivita, idFornitore, idCondominio, null, personaMessaggioDTO.TipoIndirizzo, personaMessaggioDTO.Importo, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null); oggetto = _messagisticaService.ApplicaStampaUnione(oggetto, parametri, idAzienda); testo = _messagisticaService.ApplicaStampaUnione(testo, parametri, idAzienda); } // ===================================== // Invio Messaggio // ===================================== var credenziali = _configurationService.GetLoginInfo(idAzienda); if (credenziali != null && !string.IsNullOrEmpty(credenziali.Value.Utente) && !string.IsNullOrEmpty(credenziali.Value.Password)) { var userService = new it.emessage.users.Users(); var success = false; try { var resultUsers = userService.Login(credenziali.Value.Utente, credenziali.Value.Password, null); success = resultUsers.success; } catch (Exception ex) { _log.WarnFormat("Errore durante il controllo delle credenziali - {0} - username:{1} - password:{2} - azienda:{3}", ex, Library.Utility.GetMethodDescription(), credenziali.Value.Utente, credenziali.Value.Password, idAzienda); } if (success) { var service = new Sms {Timeout = 999999999}; var identificazioneMittente = _configurationService.GetIdentificazioneMittente(idAzienda, TipoMessaggio.Sms, TipoIndirizzo.Recapito); if (!string.IsNullOrEmpty(identificazioneMittente.Email)) emailRapportino += "," + identificazioneMittente.Email; // Mittente if (string.IsNullOrEmpty(mittente)) mittente = identificazioneMittente.Nome; if (!string.IsNullOrEmpty(mittente) && mittente.Length > 11) mittente = mittente.Substring(0, 11); if (ConfigurationManager.AppSettings["IsTest"] != null && bool.Parse(ConfigurationManager.AppSettings["IsTest"])) destinatariSend = new List<string> {"+393382958239"}; var parameters = new List<OptionalParameters> { new OptionalParameters { ParameterName = "NotificationEmail", ParameterValue = emailRapportino }, new OptionalParameters { ParameterName = "DeliveryTime", ParameterValue = DateTime.Now.ToString() } }; // --------------------------------------- // Invio NON Asincrono // --------------------------------------- if (!parametriInvioLettera.Asincrono) { if (motivoMessaggio != MotivoMessaggio.ScadenzaContratto) { try { if (string.IsNullOrEmpty(parametriInvioLettera.Tipo)) parametriInvioLettera.Tipo = "NORMAL"; result = service.Send(credenziali.Value.Utente, credenziali.Value.Password, mittente, destinatariSend.ToArray(), testo, parametriInvioLettera.Tipo, parameters.ToArray()); } catch (Exception ex) { _log.FatalFormat("Errore inaspettato durante l'invio del sms - INVIO DIRETTO - {0} - oggetto:{1} - destinatari:{2} - testo:{3} - azienda:{4} - tipo:{5} - parameters:{6} - mittente:{7} - utente:{8}", ex, Library.Utility.GetMethodDescription(), oggetto, destinatariSend.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), testo, idAzienda, parametriInvioLettera.Tipo, parameters.Aggregate(string.Empty, (current, param) => current + (param + ", ")), mittente, credenziali.Value.Utente); throw; } } _log.InfoFormat("Risultato invio sms:{0} - destinatario:{1} - azienda:{2}", result, destinatariSend.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), idAzienda); if (result != null) { message += result; if (result.success) invioRiuscito = true; } } // --------------------------------------- // Invio Asincrono // --------------------------------------- else { try { service.SendCompleted += serviceSendCompleted; service.SendAsync(credenziali.Value.Utente, credenziali.Value.Password, mittente, destinatariSend.ToArray(), testo, parametriInvioLettera.Tipo, parameters.ToArray()); } catch (Exception ex) { _log.FatalFormat("Errore inaspettato durante l'invio del sms - INVIO ASINCRONO - {0} - oggetto:{1} - destinatari:{2} - testo:{3} - azienda:{4} - tipo:{5} - parameters:{6} - mittente:{7} - utente:{8}", ex, Library.Utility.GetMethodDescription(), oggetto, destinatariSend.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), testo, idAzienda, parametriInvioLettera.Tipo, parameters.Aggregate(string.Empty, (current, param) => current + (param + ", ")), mittente, credenziali.Value.Utente); throw; } // Se invio asincrono suppongo sia andato a buon fine invioRiuscito = true; results.Add(new RisultatoInvioMessaggio("N.D.", "N.D.", true, "Tutti gli sms sono stati accodati per l'invio", new DocumentInfo())); } if (invioRiuscito) { // ===================================== // Controllo rapportino // ===================================== if (parametriInvioLettera.Tipo == "NOTIFICATION") { // Crea un trigger che parte tra 10 minuti e ogni minuto per 30 volte controlla le mail in arrivo. Trigger trigger = new PeriodicTrigger(DateTime.UtcNow.AddSeconds(10), null, TimeSpan.FromMinutes(1), 30); var jobSpec = new JobSpec("Controllo rapportino", "Verifica e salvataggio email contenente rapportino di conferma di invio SMS", "ConfermaRicezioneMessaggio", trigger); _scheduler.CreateJob(jobSpec, CreateJobConflictAction.Replace); _scheduler.Start(); } } } else { _log.WarnFormat("Credenziali non valide - {0} - username:{1} - password:{2} - azienda:{3}", Library.Utility.GetMethodDescription(), credenziali.Value.Utente, credenziali.Value.Password, idAzienda); } } else { _log.FatalFormat("Errore inaspettato durante l'invio del sms. NON sono presenti le credenziali per l'invio del sms - {0} - oggetto:{1} - destinatari:{2} - azienda:{3}", Library.Utility.GetMethodDescription(), oggetto, destinatari.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), idAzienda); message = "KO - Non sono definite le credenziali per l'invio dei sms"; } } else { _log.WarnFormat("Errore inaspettato durante l'invio del sms. NON è definito nessun destinatario - {0} - oggetto:{1} - destinatari:{2} - azienda:{3}", Library.Utility.GetMethodDescription(), oggetto, destinatari.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), idAzienda); message = "KO - Non è definito nessun destinatario"; } } else { _log.WarnFormat("Errore inaspettato durante l'invio del sms. NON è definito nessun destinatario - {0} - oggetto:{1} - destinatari:{2} - azienda:{3}", Library.Utility.GetMethodDescription(), oggetto, destinatari.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), idAzienda); message = "KO - Non è definito nessun destinatario"; } } catch (Exception ex) { invioRiuscito = false; _log.ErrorFormat("Errore inaspettato durante l'invio del sms - {0} - oggetto:{1} - destinatari:{2} - azienda:{3}", ex, Library.Utility.GetMethodDescription(), oggetto, destinatari.Aggregate(string.Empty, (current, dest) => current + (dest + ", ")), idAzienda); message = "KO - Errore inaspettato durante l'invio del sms"; } // =================================================================== // Storicizzazione dei messaggi solo se l'invio non è stato asicrono // =================================================================== if (!parametriInvioLettera.Asincrono && motivoMessaggio != MotivoMessaggio.ScadenzaContratto && invioRiuscito) { results = elaboraResult(result, results); } else { if(!invioRiuscito) results.Add(new RisultatoInvioMessaggio("KO", null, false, message, new DocumentInfo())); } return results; }
protected override void OnStart(string[] args) { try { _shSferaService.Open(); _log.Info("Servizio Sfera Avviato"); _shFileTranferServiceHost.Open(); _log.Info("Servizio FileTransfer Avviato"); _log.Info("Inizio caricamento cache"); PreLoadedCollection.Instance.SetBanche(); PreLoadedCollection.Instance.SetLocalita(); _log.Info("Fine cache"); IWindsorContainer container = new WindsorContainer(); container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel, true)); container.Kernel.Resolver.AddSubResolver(new ListResolver(container.Kernel, true)); container.Install(Castle.Windsor.Installer.Configuration.FromAppConfig()); // ===================================== // Alert Contratti // ===================================== // Crea un trigger che parte tra 10 minuti e ogni minuto per 30 volte controlla le mail in arrivo. Trigger trigger = new PeriodicTrigger(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 23, 0, 0), null, TimeSpan.FromDays(1), null); // Create a job specification for my job. var jobSpec = new JobSpec("Alert Contratto", "Invio alert scadenza contratti e premi assicurativi", "AlertMessaggio", trigger); //jobSpec.JobData = jobData; // Create a job. If it already exists in the persistent store then automatically update // its definition to reflect the provided job specification. This is a good idea when using // a scheduler cluster because the job is guaranteed to be created exactly once and kept up // to date without it ever being accidentally deleted by one instance while another instance // is processing it. var scheduler = container.Resolve<IScheduler>(); scheduler.CreateJob(jobSpec, CreateJobConflictAction.Replace); // Start the scheduler. scheduler.Start(); // ===================================== // Controllo Messaggi // ===================================== // Crea un trigger che parte tra 15 minuti e controlla le info dei messaggi. Trigger triggerMessaggi = new PeriodicTrigger(DateTime.Now.AddHours(-2), null, TimeSpan.FromMinutes(15), null); // Create a job specification for my job. var jobSpecMessaggi = new JobSpec("Controllo Messaggi", "Controllo e aggiornamento info su messaggi inviati", "ControlloMessaggi", triggerMessaggi); var schedulerMessaggi = container.Resolve<IScheduler>(); schedulerMessaggi.CreateJob(jobSpecMessaggi, CreateJobConflictAction.Replace); // Start the scheduler. schedulerMessaggi.Start(); // ===================================== // Controllo rapportino // ===================================== // Crea un trigger che parte ogni 15 minuti controlla le mail in arrivo. Trigger triggerRapportino = new PeriodicTrigger(DateTime.Now.AddHours(-3), null, TimeSpan.FromMinutes(15), null); // Create a job specification for my job. var jobSpecRapportino = new JobSpec("Controllo rapportino", "Verifica e salvataggio email contenente rapportino di conferma di invio", "ConfermaRicezioneMessaggio", triggerRapportino); var schedulerRapportino = container.Resolve<IScheduler>(); schedulerRapportino.CreateJob(jobSpecRapportino, CreateJobConflictAction.Replace); // Start the scheduler. schedulerRapportino.Start(); // ===================================== // Invio Mail // ===================================== // Crea un trigger che parte subito e ogni minuto verifica e invia le mail presenti in coda. Trigger triggerMail = new PeriodicTrigger(DateTime.Now.AddHours(-1), null, TimeSpan.FromSeconds(int.Parse(ConfigurationManager.AppSettings["SendingMailDelay"])), null); // Create a job specification for my job. var jobSpecMail = new JobSpec("Invio Mail", "Invia le mail presenti nella coda di Delivery", "InvioMail", triggerMail); var schedulerMail = container.Resolve<IScheduler>(); schedulerMail.CreateJob(jobSpecMail, CreateJobConflictAction.Replace); // Start the scheduler. schedulerMail.Start(); // ===================================== // Ricezione Documenti Fatture // ===================================== // Crea un trigger che parte alle 02 di mattina per preparare il file contenente gli identificativi delle fatture da scaricare Trigger triggerRicezioneDocumentiFatture = new PeriodicTrigger(new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 01, 0, 0), null, TimeSpan.FromDays(1), null); // Create a job specification for my job. var jobRicezioneDocumentiFatture = new JobSpec("Ricezione Documenti Fatture", "Predispone il file per la ricezione dei documenti delle fatture", "RicezioneDocumentiFatture", triggerRicezioneDocumentiFatture); var schedulerRicezioneDocumentiFatture = container.Resolve<IScheduler>(); schedulerRicezioneDocumentiFatture.CreateJob(jobRicezioneDocumentiFatture, CreateJobConflictAction.Replace); // Start the scheduler. schedulerRicezioneDocumentiFatture.Start(); } catch (Exception ex) { _log.Error("Errore nell'avvio di SferaService: OnStart(string[] args)", ex); throw; } }
public void Description_ThrowsIfValueIsNull() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); spec.Description = null; }
/// <summary> /// Splits the provided job up into smaller child jobs /// </summary> /// <param name="job">The job to split.</param> /// <returns>Null as this should never be called.</returns> public SplitResult Split(JobSpec <string> job) { return(null); }
/// <summary> /// Creates a job in the database. /// </summary> /// <param name="clusterName">The cluster name, never null</param> /// <param name="jobSpec">The job specification, never null</param> /// <param name="creationTimeUtc">The job creation time</param> /// <param name="conflictAction">The action to take if a conflict occurs</param> /// <returns>True if the job was created or updated, false if a conflict occurred /// and no changes were made</returns> /// <exception cref="SchedulerException">Thrown if an error occurs</exception> public virtual bool CreateJob(string clusterName, JobSpec jobSpec, DateTime creationTimeUtc, CreateJobConflictAction conflictAction) { try { using (IDbConnection connection = CreateConnection()) { IDbCommand command = CreateStoredProcedureCommand(connection, "spSCHED_CreateJob"); CreateJobConflictActionCode conflictActionCode; switch (conflictAction) { default: case CreateJobConflictAction.Ignore: case CreateJobConflictAction.Throw: conflictActionCode = CreateJobConflictActionCode.Ignore; break; case CreateJobConflictAction.Replace: conflictActionCode = CreateJobConflictActionCode.Replace; break; case CreateJobConflictAction.Update: conflictActionCode = CreateJobConflictActionCode.Update; break; } AddInputParameter(command, "ClusterName", DbType.String, clusterName); AddInputParameter(command, "JobName", DbType.String, jobSpec.Name); AddInputParameter(command, "JobDescription", DbType.String, jobSpec.Description); AddInputParameter(command, "JobKey", DbType.String, jobSpec.JobKey); AddInputParameter(command, "TriggerObject", DbType.Binary, DbUtils.MapObjectToDbValue(DbUtils.SerializeObject(jobSpec.Trigger))); AddInputParameter(command, "JobDataObject", DbType.Binary, DbUtils.MapObjectToDbValue(DbUtils.SerializeObject(jobSpec.JobData))); AddInputParameter(command, "CreationTime", DbType.DateTime, creationTimeUtc); AddInputParameter(command, "ConflictActionCode", DbType.Int32, conflictActionCode); IDbDataParameter resultCodeParam = AddOutputParameter(command, "ResultCode", DbType.Int32); connection.Open(); command.ExecuteNonQuery(); CreateJobResultCode resultCode = (CreateJobResultCode)resultCodeParam.Value; switch (resultCode) { case CreateJobResultCode.JobCreated: case CreateJobResultCode.JobReplaced: case CreateJobResultCode.JobUpdated: return(true); case CreateJobResultCode.JobWithSameNameExists: if (conflictAction == CreateJobConflictAction.Throw) { throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "Job '{0}' already exists.", jobSpec.Name)); } return(false); default: throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "spSCHED_CreateJob returned unrecognized result code '{0}'.", resultCode)); } } } catch (Exception ex) { throw new SchedulerException("The job store was unable to create a job in the database.", ex); } }
/// <inheritdoc /> public override void UpdateJob(string existingJobName, JobSpec updatedJobSpec) { if (existingJobName == null) throw new ArgumentNullException("existingJobName"); if (existingJobName.Length == 0) throw new ArgumentException("existingJobName"); if (updatedJobSpec == null) throw new ArgumentNullException("jobSpec"); ThrowIfDisposed(); jobStoreDao.UpdateJob(clusterName, existingJobName, updatedJobSpec); }
/// <summary> /// Creates a job in the database. /// </summary> /// <param name="clusterName">The cluster name, never null</param> /// <param name="jobSpec">The job specification, never null</param> /// <param name="creationTimeUtc">The job creation time</param> /// <param name="conflictAction">The action to take if a conflict occurs</param> /// <returns>True if the job was created or updated, false if a conflict occurred /// and no changes were made</returns> /// <exception cref="SchedulerException">Thrown if an error occurs</exception> public virtual bool CreateJob(string clusterName, JobSpec jobSpec, DateTime creationTimeUtc, CreateJobConflictAction conflictAction) { try { using (IDbConnection connection = CreateConnection()) { IDbCommand command = CreateStoredProcedureCommand(connection, "spSCHED_CreateJob"); CreateJobConflictActionCode conflictActionCode; switch (conflictAction) { default: case CreateJobConflictAction.Ignore: case CreateJobConflictAction.Throw: conflictActionCode = CreateJobConflictActionCode.Ignore; break; case CreateJobConflictAction.Replace: conflictActionCode = CreateJobConflictActionCode.Replace; break; case CreateJobConflictAction.Update: conflictActionCode = CreateJobConflictActionCode.Update; break; } AddInputParameter(command, "ClusterName", DbType.String, clusterName); AddInputParameter(command, "JobName", DbType.String, jobSpec.Name); AddInputParameter(command, "JobDescription", DbType.String, jobSpec.Description); AddInputParameter(command, "JobKey", DbType.String, jobSpec.JobKey); AddInputParameter(command, "TriggerObject", DbType.Binary, DbUtils.MapObjectToDbValue(DbUtils.SerializeObject(jobSpec.Trigger))); AddInputParameter(command, "JobDataObject", DbType.Binary, DbUtils.MapObjectToDbValue(DbUtils.SerializeObject(jobSpec.JobData))); AddInputParameter(command, "CreationTime", DbType.DateTime, creationTimeUtc); AddInputParameter(command, "ConflictActionCode", DbType.Int32, conflictActionCode); IDbDataParameter resultCodeParam = AddOutputParameter(command, "ResultCode", DbType.Int32); connection.Open(); command.ExecuteNonQuery(); CreateJobResultCode resultCode = (CreateJobResultCode) resultCodeParam.Value; switch (resultCode) { case CreateJobResultCode.JobCreated: case CreateJobResultCode.JobReplaced: case CreateJobResultCode.JobUpdated: return true; case CreateJobResultCode.JobWithSameNameExists: if (conflictAction == CreateJobConflictAction.Throw) throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "Job '{0}' already exists.", jobSpec.Name)); return false; default: throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "spSCHED_CreateJob returned unrecognized result code '{0}'.", resultCode)); } } } catch (Exception ex) { throw new SchedulerException("The job store was unable to create a job in the database.", ex); } }
/// <summary> /// Builds a job details object from the result set returned by the spSCHED_GetJobDetails /// and spSCHED_GetNextJob stored procedures. /// </summary> /// <param name="reader">The reader for the result set</param> /// <returns>The job details object</returns> protected virtual VersionedJobDetails BuildJobDetailsFromResultSet(IDataReader reader) { string jobName = reader.GetString(0); string jobDescription = reader.GetString(1); string jobKey = reader.GetString(2); Trigger trigger = (Trigger) DbUtils.DeserializeObject(DbUtils.MapDbValueToObject<byte[]>(reader.GetValue(3))); JobData jobData = (JobData) DbUtils.DeserializeObject(DbUtils.MapDbValueToObject<byte[]>(reader.GetValue(4))); DateTime creationTimeUtc = DateTimeUtils.AssumeUniversalTime(reader.GetDateTime(5)); JobState jobState = (JobState) reader.GetInt32(6); DateTime? nextTriggerFireTimeUtc = DateTimeUtils.AssumeUniversalTime(DbUtils.MapDbValueToNullable<DateTime>(reader.GetValue(7))); int? nextTriggerMisfireThresholdSeconds = DbUtils.MapDbValueToNullable<int>(reader.GetValue(8)); TimeSpan? nextTriggerMisfireThreshold = nextTriggerMisfireThresholdSeconds.HasValue ? new TimeSpan(0, 0, nextTriggerMisfireThresholdSeconds.Value) : (TimeSpan?) null; Guid? lastExecutionSchedulerGuid = DbUtils.MapDbValueToNullable<Guid>(reader.GetValue(9)); DateTime? lastExecutionStartTimeUtc = DateTimeUtils.AssumeUniversalTime(DbUtils.MapDbValueToNullable<DateTime>(reader.GetValue(10))); DateTime? lastExecutionEndTimeUtc = DateTimeUtils.AssumeUniversalTime(DbUtils.MapDbValueToNullable<DateTime>(reader.GetValue(11))); bool? lastExecutionSucceeded = DbUtils.MapDbValueToNullable<bool>(reader.GetValue(12)); string lastExecutionStatusMessage = DbUtils.MapDbValueToObject<string>(reader.GetValue(13)); int version = reader.GetInt32(14); JobSpec jobSpec = new JobSpec(jobName, jobDescription, jobKey, trigger); jobSpec.JobData = jobData; VersionedJobDetails details = new VersionedJobDetails(jobSpec, creationTimeUtc, version); details.JobState = jobState; details.NextTriggerFireTimeUtc = nextTriggerFireTimeUtc; details.NextTriggerMisfireThreshold = nextTriggerMisfireThreshold; if (lastExecutionSchedulerGuid.HasValue && lastExecutionStartTimeUtc.HasValue) { JobExecutionDetails execution = new JobExecutionDetails(lastExecutionSchedulerGuid.Value, lastExecutionStartTimeUtc.Value); execution.EndTimeUtc = lastExecutionEndTimeUtc; execution.Succeeded = lastExecutionSucceeded.GetValueOrDefault(); execution.StatusMessage = lastExecutionStatusMessage == null ? "" : lastExecutionStatusMessage; details.LastJobExecutionDetails = execution; } return details; }
private void InternalUpdateJob(VersionedJobDetails existingJobDetails, JobSpec updatedJobSpec) { if (existingJobDetails.JobSpec.Name != updatedJobSpec.Name) { if (jobs.ContainsKey(updatedJobSpec.Name)) throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "Cannot rename job '{0}' to '{1}' because there already exists another job with the new name.", existingJobDetails.JobSpec.Name, updatedJobSpec.Name)); jobs.Remove(existingJobDetails.JobSpec.Name); jobs.Add(updatedJobSpec.Name, existingJobDetails); } existingJobDetails.Version += 1; existingJobDetails.JobSpec = updatedJobSpec.Clone(); if (existingJobDetails.JobState == JobState.Scheduled) existingJobDetails.JobState = JobState.Pending; Monitor.PulseAll(jobs); }
/// <inheritdoc /> public override void UpdateJob(string existingJobName, JobSpec updatedJobSpec) { if (existingJobName == null) throw new ArgumentNullException("existingJobName"); if (existingJobName.Length == 0) throw new ArgumentException("existingJobName"); if (updatedJobSpec == null) throw new ArgumentNullException("updatedJobSpec"); lock (jobs) { ThrowIfDisposed(); VersionedJobDetails existingJobDetails; if (! jobs.TryGetValue(existingJobName, out existingJobDetails)) throw new SchedulerException(String.Format(CultureInfo.CurrentCulture, "There is no existing job named '{0}'.", existingJobName)); InternalUpdateJob(existingJobDetails, updatedJobSpec); } }
public void Trigger_GetterAndSetter() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); Trigger newTrigger = PeriodicTrigger.CreateDailyTrigger(DateTime.UtcNow); spec.Trigger = newTrigger; Assert.AreSame(newTrigger, spec.Trigger); }
/// <summary> /// Checks to see if the job should skip processing. /// </summary> /// <param name="job">The job to verify</param> /// <returns>True if processing should be skipped, false otherwise.</returns> public bool SkipProcessing(JobSpec <string> job) { return(false); }
public void JobData_GetterAndSetter() { JobSpec spec = new JobSpec("abc", "some job", "with this key", trigger); JobData jobData = new JobData(); spec.JobData = jobData; Assert.AreSame(jobData, spec.JobData); }
/// <summary> /// Checks to see if the job should be split up. /// </summary> /// <param name="job">The job to verify</param> /// <returns>True if the job should be split up, false otherwise.</returns> public bool RequiresSplit(JobSpec <string> job) { return(false); }
/// <summary> /// Checks to see if the job should skip processing. /// </summary> /// <param name="job">The job to verify</param> /// <returns>True if processing should be skipped, false otherwise.</returns> public bool SkipProcessing(JobSpec <string> job) { return(job.Children.Count > 0); }
/// <summary> /// Creates job details for a newly created job. /// </summary> /// <param name="jobSpec">The job's specification</param> /// <param name="creationTime">The time when the job was created</param> /// <param name="version">The version number</param> /// <exception cref="ArgumentNullException">Thrown when <paramref name="jobSpec"/> is null</exception> public VersionedJobDetails(JobSpec jobSpec, DateTime creationTime, int version) : base(jobSpec, creationTime) { this.version = version; }
public string ControlloRapportinoMessaggio() { var message = string.Empty; try { // ===================================== // Controllo rapportino // ===================================== //Gipasoft.Business.ConfirmReceiveMessage.ConfirmReceiveMessageService serv = new Gipasoft.Business.ConfirmReceiveMessage.ConfirmReceiveMessageService(null); //serv.Test(_praticaService); // Crea un trigger che parte subito e controlla 1 volta controlla le mail in arrivo. Trigger trigger = PeriodicTrigger.CreateOneShotTrigger(DateTime.UtcNow.AddSeconds(10)); // Create a job specification for my job. var jobSpec = new JobSpec("Controllo rapportino singolo", "Verifica e salvataggio email contenente rapportino di conferma di invio FAX", "ConfermaRicezioneMessaggio", trigger); //jobSpec.JobData = jobData; // Create a job. If it already exists in the persistent store then automatically update // its definition to reflect the provided job specification. This is a good idea when using // a scheduler cluster because the job is guaranteed to be created exactly once and kept up // to date without it ever being accidentally deleted by one instance while another instance // is processing it. _scheduler.CreateJob(jobSpec, CreateJobConflictAction.Replace); // Start the scheduler. _scheduler.Start(); } catch (Exception ex) { _log.ErrorFormat("Errore inaspettato durante il controllo del rapportino di invio fax - {0}", ex, Utility.GetMethodDescription()); message = "KO - Errore inaspettato durante il controllo del rapportino di invio del fax"; } return message; }
/// <summary> /// Checks to see if the job should be split up. /// </summary> /// <param name="job">The job to verify</param> /// <returns>True if the job should be split up, false otherwise.</returns> public bool RequiresSplit(JobSpec <string> job) { var jobData = JsonConvert.DeserializeObject <MarketDataImport>(job.Data); return(jobData.MarketTypeIds.Count > 5); }