public void JobParametersTest() { JobParameters jp = new JobParameters(); Assert.IsNotNull(jp); Assert.IsNotNull(jp.GetParameters()); Assert.AreEqual(0,jp.GetParameters().Count); }
public override bool OnStartJob(JobParameters @params) { var updater = new CalendarTask(this, @params); updater.Execute(); return(true); }
public override bool OnStartJob(JobParameters @params) { Log.Error("lv", "222222222222222"); Intent notIntent = new Intent(this, typeof(MainActivity)); PendingIntent contentIntent = PendingIntent.GetActivity(this, 0, notIntent, PendingIntentFlags.UpdateCurrent); NotificationManagerCompat manager = NotificationManagerCompat.From(this); var wearableExtender = new NotificationCompat.WearableExtender().SetBackground(BitmapFactory.DecodeResource(this.Resources, Resource.Drawable.pause)); NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .SetContentIntent(contentIntent) .SetSmallIcon(Resource.Drawable.play) .SetContentTitle("title") .SetContentText("message") .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis()) .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) .Extend(wearableExtender); Notification notification = builder.Build(); notification.Flags = NotificationFlags.AutoCancel; manager.Notify(0, notification); JobFinished(@params, false); return(true); }
private void runSync(JobParameters parameters) { var dependencyContainer = AndroidDependencyContainer.Instance; if (!dependencyContainer.UserAccessManager.CheckIfLoggedIn()) { finishJobClearingPendingSyncJobLock(parameters); return; } var shouldHandlePushNotifications = dependencyContainer .RemoteConfigService .GetPushNotificationsConfiguration() .HandlePushNotifications; if (shouldHandlePushNotifications) { var interactorFactory = dependencyContainer.InteractorFactory; var syncInteractor = Application.IsInForeground ? interactorFactory.RunPushNotificationInitiatedSyncInForeground() : interactorFactory.RunPushNotificationInitiatedSyncInBackground(); syncInteractor.Execute().Wait(); } finishJobClearingPendingSyncJobLock(parameters); }
/// <summary> /// Creates a row mapper for job executions. /// </summary> /// <param name="jobInstance">the job instance of the executions to create (optional)</param> /// <returns>a row mapper for job executions</returns> private RowMapper <JobExecution> GetJobExecutionRowMapper(JobInstance jobInstance = null) { JobParameters jobParameters = null; return((dataRecord, i) => { var wrapper = new DataRecordWrapper(dataRecord); var id = wrapper.Get <long>(0); var jobConfigurationLocation = wrapper.Get <string>(9); if (jobParameters == null) { jobParameters = GetJobParameters(id); } var jobExecution = jobInstance == null ? new JobExecution(id, jobParameters, jobConfigurationLocation) : new JobExecution(jobInstance, id, jobParameters, jobConfigurationLocation); jobExecution.StartTime = wrapper.Get <DateTime?>(1); jobExecution.EndTime = wrapper.Get <DateTime?>(2); jobExecution.Status = dataRecord.IsDBNull(3) ? null : BatchStatus.ValueOf(dataRecord.GetString(3)); jobExecution.ExitStatus = new ExitStatus(wrapper.Get <string>(4), wrapper.Get <string>(5)); jobExecution.CreateTime = wrapper.Get <DateTime>(6); jobExecution.LastUpdated = wrapper.Get <DateTime?>(7); jobExecution.Version = wrapper.Get <int?>(8); return jobExecution; }); }
/// <summary> /// Creates a job instance with given name and parameters. /// A job instance with the same name and parameters should not already exist. /// </summary> /// <param name="jobName">the job name</param> /// <param name="jobParameters">job parameters</param> /// <returns>a new persisted job instance</returns> public JobInstance CreateJobInstance(string jobName, JobParameters jobParameters) { Assert.NotNull(jobName, "Job name must not be null"); Assert.NotNull(jobParameters, "Job parameters must not be null"); Assert.State(GetJobInstance(jobName, jobParameters) == null, "A job instance with this combination of name and parameters must not already exist"); using (var scope = new TransactionScope(TransactionScopeOption.Required, TransactionOptions)) { var jobId = _jobIncrementer.NextLong(); var jobInstance = new JobInstance(jobId, jobName); jobInstance.IncrementVersion(); var parameters = new Dictionary <string, object> { { "id", jobId }, { "jobName", jobName }, { "key", _jobKeyGenerator.GenerateKey(jobParameters) }, { "version", jobInstance.Version } }; DbOperator.Update(InsertTablePrefix(CreateJobInstanceQuery), parameters); scope.Complete(); return(jobInstance); } }
private async Task CheckRecurringPayments(JobParameters args) { try { Debug.WriteLine("RecurringPayment Job started."); DataAccess.ApplicationContext.DbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DatabaseConstants.DB_NAME); var ambientDbContextLocator = new AmbientDbContextLocator(); var dbContextScopeFactory = new DbContextScopeFactory(); await new RecurringPaymentManager( new RecurringPaymentService(ambientDbContextLocator, dbContextScopeFactory), new PaymentService(ambientDbContextLocator, dbContextScopeFactory)) .CreatePaymentsUpToRecur(); Debug.WriteLine("RecurringPayment Job finished."); JobFinished(args, false); } catch (Exception ex) { Debug.Write(ex); } }
private string CreateBootstrapAvroJobConfig(JobParameters jobParameters, string driverFolder) { var bootstrapJobArgs = new AvroJobSubmissionParameters { jobSubmissionFolder = driverFolder, jobId = jobParameters.JobIdentifier, }; var bootstrapLocalJobArgs = new AvroLocalJobSubmissionParameters { sharedJobSubmissionParameters = bootstrapJobArgs, driverStdoutFilePath = jobParameters.StdoutFilePath.IsPresent() ? jobParameters.StdoutFilePath.Value : _fileNames.GetDriverStdoutFileName(), driverStderrFilePath = jobParameters.StderrFilePath.IsPresent() ? jobParameters.StderrFilePath.Value : _fileNames.GetDriverStderrFileName() }; var submissionArgsFilePath = Path.Combine(driverFolder, _fileNames.GetJobSubmissionParametersFile()); using (var argsFileStream = new FileStream(submissionArgsFilePath, FileMode.CreateNew)) { var serializedArgs = AvroJsonSerializer <AvroLocalJobSubmissionParameters> .ToBytes(bootstrapLocalJobArgs); argsFileStream.Write(serializedArgs, 0, serializedArgs.Length); } return(submissionArgsFilePath); }
public void Initialize() { _jobExecutionDao = new MapJobExecutionDao(); _instance = new JobInstance(1, "testJob"); _parameters = new JobParameters(); _execution = new JobExecution(_instance, _parameters); }
private string GetCommand(JobParameters jobParameters) { var commandProviderConfigModule = AzureBatchCommandBuilderConfiguration.ConfigurationModule; if (jobParameters.JavaLogLevel == JavaLoggingSetting.Verbose) { commandProviderConfigModule = commandProviderConfigModule .Set(AzureBatchCommandBuilderConfiguration.JavaDebugLogging, true.ToString().ToLowerInvariant()); } if (jobParameters.StdoutFilePath.IsPresent()) { commandProviderConfigModule = commandProviderConfigModule .Set(AzureBatchCommandBuilderConfiguration.DriverStdoutFilePath, jobParameters.StdoutFilePath.Value); } if (jobParameters.StderrFilePath.IsPresent()) { commandProviderConfigModule = commandProviderConfigModule .Set(AzureBatchCommandBuilderConfiguration.DriverStderrFilePath, jobParameters.StderrFilePath.Value); } var azureBatchJobCommandBuilder = _injector.ForkInjector(commandProviderConfigModule.Build()) .GetInstance <ICommandBuilder>(); var command = azureBatchJobCommandBuilder.BuildDriverCommand(jobParameters.DriverMemoryInMB); return(command); }
private async Task ClearPayments(JobParameters args) { try { Debug.WriteLine("ClearPayments Job started"); DataAccess.ApplicationContext.DbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DatabaseConstants.DB_NAME); var paymentService = new PaymentService(new AmbientDbContextLocator(), new DbContextScopeFactory()); var payments = await paymentService.GetUnclearedPayments(DateTime.Now); var unclearedPayments = payments.ToList(); if (unclearedPayments.Any()) { Debug.WriteLine("Payments for clearing found."); await paymentService.SavePayments(unclearedPayments.ToArray()); } Debug.WriteLine("ClearPayments Job finished."); JobFinished(args, false); } catch (Exception ex) { Crashes.TrackError(ex); Debug.Write(ex); } }
internal byte[] SerializeJobArgsToBytes(JobParameters jobParameters, string driverFolderPath) { var avroJobSubmissionParameters = new AvroJobSubmissionParameters { jobId = jobParameters.JobIdentifier, jobSubmissionFolder = driverFolderPath }; var avroYarnJobSubmissionParameters = new AvroYarnJobSubmissionParameters { sharedJobSubmissionParameters = avroJobSubmissionParameters, fileSystemUrl = _fileSystemUrl, jobSubmissionDirectoryPrefix = _jobSubmissionPrefix }; var avroYarnClusterJobSubmissionParameters = new AvroYarnClusterJobSubmissionParameters { // TODO[JIRA REEF-1887] Deprecated. Remove in REEF 0.18. securityTokenKind = _securityTokenKind, securityTokenService = _securityTokenService, yarnJobSubmissionParameters = avroYarnJobSubmissionParameters, driverMemory = jobParameters.DriverMemoryInMB, maxApplicationSubmissions = jobParameters.MaxApplicationSubmissions, driverStdoutFilePath = string.IsNullOrWhiteSpace(jobParameters.StdoutFilePath.Value) ? _fileNames.GetDefaultYarnDriverStdoutFilePath() : jobParameters.StdoutFilePath.Value, driverStderrFilePath = string.IsNullOrWhiteSpace(jobParameters.StderrFilePath.Value) ? _fileNames.GetDefaultYarnDriverStderrFilePath() : jobParameters.StderrFilePath.Value }; return(AvroJsonSerializer <AvroYarnClusterJobSubmissionParameters> .ToBytes(avroYarnClusterJobSubmissionParameters)); }
private async Task DoBackGroundWork(JobParameters @params) { var instans = new Notifications(); #pragma warning disable CS4014 Task.Run(async() => { var ss = new StoredSearch(); var liste = await ss.GetAll(); if (liste.Count > 0) { var ws = new ScraperFacade(); var vareListe = await ws.GetVareMultiSearch(liste, cts); if (vareListe.Count > 0) { instans.SendNotification("Goods of interest found!", "Check out your Price Checker app " + vareListe.Count + " goods of interest"); vareListe.ForEach(async o => { var cacheObj = new CachedVare { MaxPris = o.MaxPris, MinPris = o.MinPris, Navn = o.Navn, Pris = o.Pris, Url = o.Url }; if (!await cacheObj.DuplicateCheck()) { await cacheObj.Save(); } }); } } JobFinished(@params, false); } ); #pragma warning restore CS4014 }
public void EqualsTest() { IDictionary <string, JobParameter> myJobP = new Dictionary <string, JobParameter> { { "p1", new JobParameter("param1") }, { "p2", new JobParameter(2) }, { "p3", new JobParameter(3.0) }, { "p4", new JobParameter(DateTime.Parse("1970-07-31")) } }; JobParameters jp = new JobParameters(myJobP); //NOTE : ORDER DOES NOT COUNT ON EQUALS COMPARISON, ONLY <KEY,VALUES> //SAME BEHAVIOUR AS LinkedHashMap IDictionary <string, JobParameter> myJobP2 = new Dictionary <string, JobParameter> { { "p2", new JobParameter(2) }, { "p1", new JobParameter("param1") }, { "p3", new JobParameter(3.0) }, { "p4", new JobParameter(DateTime.Parse("1970-07-31")) } }; JobParameters jp2 = new JobParameters(myJobP2); JobParameters jp3 = new JobParameters(); Assert.IsTrue(DictionaryUtils <string, JobParameter> .AreEqual(myJobP, myJobP2)); Assert.IsTrue(jp.Equals(jp2)); Assert.IsFalse(jp.Equals(jp3)); }
private async Task SyncBackups(JobParameters args) { if (!Mvx.IoCProvider.CanResolve <IMvxFileStore>()) { return; } try { DataAccess.ApplicationContext.DbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DatabaseConstants.DB_NAME); await new BackupManager(new OneDriveService(new OneDriveAuthenticator()), Mvx.IoCProvider.Resolve <IMvxFileStore>(), new SettingsManager(new SettingsAdapter()), new ConnectivityImplementation()) .DownloadBackup(); JobFinished(args, false); } catch (Exception ex) { Debug.Write(ex); } }
public override bool OnStartJob(JobParameters @params) { try { Task.Run(async() => { try { var item = new LoggerItem() { Time = DateTime.Now.ToString("HH:mm:ss"), Content = "JobService OnStartJob called" }; Log.Information(item.Content); await App.Database.SaveItemAsync(item); } catch (Exception e) { Log.Error(e.Message); } }); } catch (Exception e) { Log.Error(e.Message); } finally { JobFinished(@params, needsReschedule: false); } return(true); }
public void TestGetJobInstances() { IDictionary <string, JobParameter> params2 = new OrderedDictionary <string, JobParameter>(2); params2["param"] = new JobParameter("test"); var parameters2 = new JobParameters(params2); IDictionary <string, JobParameter> params3 = new OrderedDictionary <string, JobParameter>(2); params3["param"] = new JobParameter(1); var parameters3 = new JobParameters(params3); IDictionary <string, JobParameter> params4 = new OrderedDictionary <string, JobParameter>(2); params4["param"] = new JobParameter(2); var parameters4 = new JobParameters(params4); _jobInstanceDao.CreateJobInstance("testJob", _parameters); var instance2 = _jobInstanceDao.CreateJobInstance("testJob", parameters2); var instance3 = _jobInstanceDao.CreateJobInstance("testJob", parameters3); _jobInstanceDao.CreateJobInstance("testJob", parameters4); _jobInstanceDao.CreateJobInstance("testJob2", _parameters); var instances = _jobInstanceDao.GetJobInstances("testJob", 1, 2); Assert.AreEqual(2, instances.Count); Assert.AreEqual(instance3, instances[0]); Assert.AreEqual(instance2, instances[1]); }
/// <summary> /// Validate job parameters (delegates to each validator). /// </summary> /// <param name="parameters"></param> /// <exception cref="JobParametersInvalidException"> </exception> public void Validate(JobParameters parameters) { foreach (var validator in Validators) { validator.Validate(parameters); } }
///<summary> /// Returns the job instance for the given job name and parameters. /// </summary> /// <param name="jobName">a job name</param> /// <param name="jobParameters">job parameters</param> /// <returns>the job instance with the given name and parameters or <c>null</c> if it does not exist</returns> public JobInstance GetJobInstance(string jobName, JobParameters jobParameters) { Assert.NotNull(jobName, "Job name must not be null"); Assert.NotNull(jobParameters, "Job parameters must not be null"); using (var scope = new TransactionScope(TransactionScopeOption.Required, TransactionOptions)) { var jobKey = _jobKeyGenerator.GenerateKey(jobParameters); var parameters = new Dictionary <string, object> { { "jobName", jobName }, { "key", jobKey } }; var instances = DbOperator.Select(InsertTablePrefix(string.IsNullOrWhiteSpace(jobKey) ? FindJobsWithEmptyKey : FindJobsWithKeyQuery), _rowMapper, parameters); if (instances.Count == 0) { return(null); } Assert.State(instances.Count == 1); scope.Complete(); return(instances[0]); } }
private async Task SyncBackupsAsync(JobParameters args) { var settingsFacade = new SettingsFacade(new SettingsAdapter()); if (!settingsFacade.IsBackupAutouploadEnabled || !settingsFacade.IsLoggedInToBackupService) { return; } try { var backupService = ServiceLocator.Current.GetInstance <IBackupService>(); await backupService.RestoreBackupAsync(); var mediator = ServiceLocator.Current.GetInstance <IMediator>(); await mediator.Send(new ClearPaymentsCommand()); await mediator.Send(new CreateRecurringPaymentsCommand()); logger.Info("Backup synced."); JobFinished(args, false); } catch (Exception ex) { logger.Fatal(ex); throw; } finally { settingsFacade.LastExecutionTimeStampSyncBackup = DateTime.Now; } }
public override bool OnStartJob(JobParameters @params) { // Background sync for Android 10 is temporary disabled due to a crash on Android 10 that is hard to reproduce // Calling JobFinished and returning early here stops the background job from running if (QApis.AreAvailable) { JobFinished(@params, false); return(false); } AndroidDependencyContainer.EnsureInitialized(ApplicationContext); var dependencyContainer = AndroidDependencyContainer.Instance; if (!dependencyContainer.UserAccessManager.CheckIfLoggedIn()) { return(false); } disposable = dependencyContainer.InteractorFactory.RunBackgroundSync() .Execute() .Subscribe(DoNothing, DoNothing, () => JobFinished(@params, false)); return(true); }
/// <summary> /// Called, when the job started. /// </summary> /// <param name="params"></param> /// <returns></returns> public override bool OnStartJob(JobParameters @params) { var jobs = @params.Extras.GetStringArray("jobs"); var encryption = @params.Extras.GetString("encryption"); foreach (var item in jobs) { var job = JObject.Parse(item); //Create a new instance of the background job. var jobType = Type.GetType((string)job.GetValue("job")); if (jobType == null) { JobFinished(@params, false); return(false); } var encryptionKey = JsonConvert.DeserializeObject <EncryptionKey>(encryption); var backgroundJob = (BaseBackgroundJob)Activator.CreateInstance(jobType, (int)job.GetValue("id"), new DatabaseService(new Sqlite(), encryptionKey), new Notification()); backgroundJob.Init((string)job.GetValue("data")); _parameters = @params; _serviceTask = new BackgroundServiceTask(this); _serviceTask.Execute(backgroundJob); } return(true); }
/// <summary> /// @see IJobOperator#Start . /// </summary> /// <param name="jobName"></param> /// <param name="parameters"></param> /// <returns></returns> /// <exception cref="NoSuchJobException"></exception> /// <exception cref="JobInstanceAlreadyExistsException"></exception> /// <exception cref="JobParametersInvalidException"></exception> public long?Start(string jobName, string parameters) { _logger.Info("Checking status of job with name= {0}", jobName); JobParameters jobParameters = _jobParametersConverter.GetJobParameters(PropertiesConverter.StringToProperties(parameters)); if (JobRepository.IsJobInstanceExists(jobName, jobParameters)) { throw new JobInstanceAlreadyExistsException(string.Format("Cannot start a job instance that already exists with name={0} and parameters={1}", jobName, parameters)); } IJob job = JobRegistry.GetJob(jobName); _logger.Info("Attempting to launch job with name={0} and parameters={1}", jobName, parameters); try { return(JobLauncher.Run(job, jobParameters).Id); } catch (JobExecutionAlreadyRunningException e) { throw new UnexpectedJobExecutionException(string.Format(IllegalStateMsg, "job execution already running", jobName, parameters), e); } catch (JobRestartException e) { throw new UnexpectedJobExecutionException(string.Format(IllegalStateMsg, "job not restartable", jobName, parameters), e); } catch (JobInstanceAlreadyCompleteException e) { throw new UnexpectedJobExecutionException(string.Format(IllegalStateMsg, "job already complete", jobName, parameters), e); } }
public override bool OnStartJob(JobParameters @params) { locationManager = (LocationManager)ApplicationContext.GetSystemService(Context.LocationService); locationManager.RequestLocationUpdates(LocationManager.GpsProvider, 1000L, 0.1f, this); return(true); }
private async Task CheckRecurringPayments(JobParameters args) { var settingsManager = new SettingsManager(new SettingsAdapter()); try { Debug.WriteLine("RecurringPayment Job started."); DataAccess.ApplicationContext.DbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DatabaseConstants.DB_NAME); var ambientDbContextLocator = new AmbientDbContextLocator(); var dbContextScopeFactory = new DbContextScopeFactory(); await new RecurringPaymentManager( new RecurringPaymentService(ambientDbContextLocator, dbContextScopeFactory), new PaymentService(ambientDbContextLocator, dbContextScopeFactory)) .CreatePaymentsUpToRecur(); Debug.WriteLine("RecurringPayment Job finished."); JobFinished(args, false); } catch (Exception ex) { Crashes.TrackError(ex); } finally { settingsManager.LastExecutionTimeStampRecurringPayments = DateTime.Now; } }
private async Task CheckRecurringPayments(JobParameters args) { var settingsManager = new SettingsFacade(new SettingsAdapter()); try { Debug.WriteLine("RecurringPayment Job started."); EfCoreContext.DbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), DatabaseConstants.DB_NAME); var context = new EfCoreContext(); await new RecurringPaymentAction(new RecurringPaymentDbAccess(context)).CreatePaymentsUpToRecur(); context.SaveChanges(); Debug.WriteLine("RecurringPayment Job finished."); JobFinished(args, false); } catch (Exception ex) { Crashes.TrackError(ex); } finally { settingsManager.LastExecutionTimeStampRecurringPayments = DateTime.Now; } }
private async Task JobHandler(JobParameters @params) { if (_cancellationSource != null) { Log.Warning(new ArgumentException(nameof(_cancellationSource)), "Cancellation token source non-null on start job"); _cancellationSource.Cancel(); } try { Log.Debug("Sync job handler running"); _cancellationSource = new CancellationTokenSource(); var syncResult = await App.Sync.Synchronize(_cancellationSource.Token); Log.Debug("Sync job completing with {0}: {1} points uploaded in {2} chunks", (syncResult.HasFailed) ? "failure" : "success", syncResult.PointsUploaded, syncResult.ChunksUploaded); JobFinished(@params, false); } finally { _cancellationSource = null; } Log.Debug("Sync job handler terminated"); }
/// <summary> /// Inserts job parameters into the job parameters table. /// </summary> /// <param name="executionId">the id of the job execution</param> /// <param name="jobParameters">job parameters to insert</param> private void InsertJobParameters(long?executionId, JobParameters jobParameters) { foreach (var pair in jobParameters) { var jobParameter = pair.Value; InsertParameter(executionId, jobParameter.Type, pair.Key, jobParameter.Value, jobParameter.Identifying); } }
public override bool OnStopJob(JobParameters parm) { Log.Debug(TAG, "OnStopJob"); // return true to indicate to the JobManager whether you'd like to reschedule // this job based on the retry criteria provided at job creation-time; return(true); }
public override bool OnStartJob(JobParameters args) { Log.Info(TAG, "on start job: " + args.JobId); DoBackgroundWork(args); return(true); }
public override bool OnStartJob(JobParameters @params) { this.parameters = @params; tsk = new JobTask(this); Toast.MakeText(Application.Context.ApplicationContext, "oops it has been sttttt", ToastLength.Short).Show(); tsk.Execute(); return(true); }
public override bool OnStopJob(JobParameters @params) { // this is the place where resources should be released // it is called when job finished prematurely // return true if job has to be rescheduled return(true); }
/// <summary> /// @see IJobInstanceDao#CreateJobInstance. /// </summary> /// <param name="jobName"></param> /// <param name="jobParameters"></param> /// <returns></returns> public JobInstance CreateJobInstance(string jobName, JobParameters jobParameters) { Assert.State(GetJobInstance(jobName, jobParameters) == null, "A job instance with this name and parameters should not already exist"); JobInstance jobInstance = new JobInstance(Interlocked.Increment(ref _currentId), jobName); jobInstance.IncrementVersion(); _jobInstances[GetKey(jobName, jobParameters)] = jobInstance; return jobInstance; }
/// <summary> /// Copy constructor. Initializes the builder with the supplied parameters. /// THIS SHOULD PRESERVE PRIOR EXISTING ORDER. /// </summary> /// <param name="jobParameters"></param> public JobParametersBuilder(JobParameters jobParameters) { _parameterMap = new OrderedDictionary<string, JobParameter>(jobParameters.GetParameters().Count); IDictionary<string, JobParameter> givenJobParameters = jobParameters.GetParameters(); KeyValuePair<string, JobParameter>[] jbArray = new KeyValuePair<string, JobParameter>[givenJobParameters.Count]; jobParameters.GetParameters().CopyTo(jbArray, 0); foreach (KeyValuePair<string, JobParameter> mapEntry in jbArray) { _parameterMap.Add(mapEntry); } }
private static JobParameters TearUp() { IDictionary<string, JobParameter> myJobP = new OrderedDictionary<string, JobParameter> { {"p1", new JobParameter("param1")}, {"p2", new JobParameter(2)}, {"p3", new JobParameter(3.0)}, {"p4", new JobParameter(DateTime.Parse("1970-07-31"))} }; JobParameters jp = new JobParameters(myJobP); return jp; }
public void GenerateKeyTest() { IDictionary<string, JobParameter> myJobP = new Dictionary<string, JobParameter> { {"p1", new JobParameter("param1")}, {"p2", new JobParameter(2)}, {"p3", new JobParameter(3.0)}, {"p4", new JobParameter(DateTime.Parse("1970-07-31"))} }; JobParameters jp = new JobParameters(myJobP); DefaultJobKeyGenerator dkg = new DefaultJobKeyGenerator(); string key = dkg.GenerateKey(jp); Assert.IsNotNull(key); Assert.AreEqual("1d07b3d07378e9fd9afa323fd8c69cc0", key); }
public new void Initialize() { base.Initialize(); _jobInstanceDao = new DbJobInstanceDao { DbOperator = DbOperator, PlaceholderGetter = new PlaceholderGetter(name => "@" + name, true), JobIncrementer = new SqlServerIncrementer { IncrementerName = "BATCH_JOB_SEQ", ConnectionStringSettings = ConnectionStringSettings, ColumnName = "ID" } }; _parameters = new JobParameters(); }
public void TestSaveJobExecution() { ResetSequence("BATCH_JOB_EXECUTION_SEQ"); Insert(@"TestData\DbDao\JobExecutionTestData1.xml"); var dictionary = new Dictionary<string, JobParameter>(); dictionary["string"] = new JobParameter("string"); dictionary["long"] = new JobParameter(3); dictionary["double"] = new JobParameter(4.3); dictionary["date"] = new JobParameter(DateTime.Now); _parameters = new JobParameters(dictionary); _execution = new JobExecution(_instance, _parameters); _jobExecutionDao.SaveJobExecution(_execution); Assert.AreEqual(1L, _execution.Id); Assert.AreEqual(_execution, _jobExecutionDao.GetJobExecution(1L)); }
public new void Initialize() { base.Initialize(); _jobExecutionDao = new DbJobExecutionDao { DbOperator = DbOperator, PlaceholderGetter = new PlaceholderGetter(name => "@" + name, true), JobIncrementer = new SqlServerIncrementer { IncrementerName = "BATCH_JOB_EXECUTION_SEQ", ConnectionStringSettings = ConnectionStringSettings, ColumnName = "ID" } }; _instance = new JobInstance(1, "TestJob"); _parameters = new JobParameters(); _execution = new JobExecution(_instance, _parameters); }
/// <summary> /// Runs the provided job with the given <see cref="JobParameters"/>. The /// JobParameters will be used to determine if this is an execution /// of an existing job instance, or if a new one should be created. /// </summary> /// <param name="job"></param> /// <param name="jobParameters"></param> /// <returns></returns> /// <exception cref="JobRestartException"> if the execution would be a re-start, but a re-start is either not allowed or not needed.</exception> /// <exception cref="JobExecutionAlreadyRunningException"> if the JobInstance already exists and has an execution already running</exception> /// <exception cref="JobInstanceAlreadyCompleteException"> if this instance has already completed successfully</exception> /// <exception cref="JobParametersInvalidException"> if given parameters do not pass validation process</exception> public JobExecution Run(IJob job, JobParameters jobParameters) { Assert.NotNull(job, "The job must be not null"); Assert.NotNull(jobParameters, "The job parameters must be not null"); JobExecution lastExecution = _jobRepository.GetLastJobExecution(job.Name, jobParameters); //manage last execution if needed HandleLastExecution(job, lastExecution); //validate Parameters job.JobParametersValidator.Validate(jobParameters); //create new job execution var jobExecution = _jobRepository.CreateJobExecution(job.Name, jobParameters); //make an creation to be able to create a task, that will be executed by given TaskExecutor as expected var jobAction = CreateJobAction(job, jobParameters, jobExecution); using (var jobTask = new Task(jobAction)) { try { _taskExecutor.Execute(jobTask); //in case of asynchronous executor ... jobTask.Wait(); } catch (InvalidOperationException exception) { jobExecution.UpgradeStatus(BatchStatus.Failed); if (jobExecution.ExitStatus.Equals(ExitStatus.Unknown)) { jobExecution.ExitStatus = ExitStatus.Failed.AddExitDescription(exception); } _jobRepository.Update(jobExecution); } } return jobExecution; }
/// <summary> /// Action creation helper. /// Given a job, job parameters and a job execution, /// will wrap the execution of the job into a <see cref="System.Action"/>. /// </summary> /// <param name="job">the job to execute</param> /// <param name="jobParameters">the job parameters</param> /// <param name="jobExecution">the job execution</param> /// <returns></returns> private static Action CreateJobAction(IJob job, JobParameters jobParameters, JobExecution jobExecution) { Action jobAction = (() => { try { Logger.Info("Job: [{0} ] launched with the following parameters:[{1}]",job,jobParameters); job.Execute(jobExecution); Logger.Info("Job: [{0}] completed with the following parameters:[{1}] and the following status: [{2}]", job,jobParameters,jobExecution.Status); } catch (Exception exception) { Logger.Info("Job: [{0}] failed unexpectedly and fatally with the following parameters: [{1}]",job,exception); throw; } }); return jobAction; }
/** * Receives callback from the service when a job has landed * on the app. Colours the UI and post a message to * uncolour it after a second. */ public void OnReceivedStartJob (JobParameters args) { showStartView.SetBackgroundColor (startJobColor); var m = Message.Obtain (handler, MessageUncolorStart); handler.SendMessageDelayed (m, 1000L); // uncolour in 1 second. paramsTextView.Text = ("Executing: " + args.JobId + " " + args.Extras); }
/// <summary> /// Custom constructor using an id and JobParameters. /// </summary> /// <param name="id"></param> /// <param name="jobParameters"></param> public JobExecution(long id, JobParameters jobParameters) : this(null, id, jobParameters, null) { }
/// <summary> /// Constructor for transient (unsaved) instances. /// </summary> /// <param name="job"></param> /// <param name="jobParameters"></param> public JobExecution(JobInstance job, JobParameters jobParameters) : this(job, null, jobParameters, null) { }
public void EqualsTest() { IDictionary<string, JobParameter> myJobP = new Dictionary<string, JobParameter> { {"p1", new JobParameter("param1")}, {"p2", new JobParameter(2)}, {"p3", new JobParameter(3.0)}, {"p4", new JobParameter(DateTime.Parse("1970-07-31"))} }; JobParameters jp = new JobParameters(myJobP); //NOTE : ORDER DOES NOT COUNT ON EQUALS COMPARISON, ONLY <KEY,VALUES> //SAME BEHAVIOUR AS LinkedHashMap IDictionary<string, JobParameter> myJobP2 = new Dictionary<string, JobParameter> { {"p2", new JobParameter(2)}, {"p1", new JobParameter("param1")}, {"p3", new JobParameter(3.0)}, {"p4", new JobParameter(DateTime.Parse("1970-07-31"))} }; JobParameters jp2 = new JobParameters(myJobP2); JobParameters jp3 = new JobParameters(); Assert.IsTrue(DictionaryUtils<string,JobParameter>.AreEqual(myJobP,myJobP2)); Assert.IsTrue(jp.Equals(jp2)); Assert.IsFalse(jp.Equals(jp3)); }
/// <summary> /// Check the parameters meet the specification provided. If optional keys /// are explicitly specified then all keys must be in that list, or in the /// required list. Otherwise all keys that are specified as required must be /// present. /// </summary> /// <param name="parameters"></param> /// <exception cref="JobParametersInvalidException"> </exception> public void Validate(JobParameters parameters) { if (parameters == null) { throw new JobParametersInvalidException("The JobParameters can not be null"); } HashSet<string> keys = new HashSet<string>(parameters.GetParameters().Keys); // If there are explicit optional keys then all keys must be in that // group, or in the required group. if (OptionalKeys.Any()) { ICollection<string> missingKeys = new HashSet<string>(); foreach (string key in keys) { if (!OptionalKeys.Contains(key) && !RequiredKeys.Contains(key)) { missingKeys.Add(key); } } if (missingKeys.Any()) { throw new JobParametersInvalidException( string.Format("The JobParameters contains keys that are not explicitly optional or required: {0} " , missingKeys)); } } ICollection<string> missingKeys2 = new HashSet<string>(); foreach (string key in RequiredKeys) { if (!keys.Contains(key)) { missingKeys2.Add(key); } } if (missingKeys2.Any()) { throw new JobParametersInvalidException( string.Format("The JobParameters do not contain required keys: {0}", missingKeys2)); } }
/// <summary> /// Creates JobExecution. /// </summary> /// <param name="jobName"></param> /// <param name="jobParameters"></param> /// <returns></returns> public JobExecution CreateJobExecution(string jobName, JobParameters jobParameters) { Assert.NotNull(jobName, "Job name must not be null."); Assert.NotNull(jobParameters, "JobParameters must not be null."); var jobInstance = _jobInstanceDao.GetJobInstance(jobName, jobParameters); ExecutionContext executionContext; // existing job instance found if (jobInstance != null) { var executions = _jobExecutionDao.FindJobExecutions(jobInstance); // check for running executions and find the last started foreach (var execution in executions) { if (execution.IsRunning()) { throw new JobExecutionAlreadyRunningException(string.Format("A job execution for this job is already running: {0}", jobInstance)); } var status = execution.Status; if (execution.JobParameters.GetParameters().Any() && (status == BatchStatus.Completed || status == BatchStatus.Abandoned)) { throw new JobInstanceAlreadyCompleteException(string.Format( "A job instance already exists and is complete for parameters={0}" + ". If you want to run this job again, change the parameters.", jobParameters)); } } executionContext = _executionContextDao.GetExecutionContext(_jobExecutionDao.GetLastJobExecution(jobInstance)); } else { // no job found, create one jobInstance = _jobInstanceDao.CreateJobInstance(jobName, jobParameters); executionContext = new ExecutionContext(); } var jobExecution = new JobExecution(jobInstance, jobParameters, null) { ExecutionContext = executionContext, LastUpdated = DateTime.Now }; // Save the JobExecution so that it picks up an ID (useful for clients // monitoring asynchronous executions): _jobExecutionDao.SaveJobExecution(jobExecution); _executionContextDao.SaveExecutionContext(jobExecution); return jobExecution; }
public void GetPropertiesTest() { //OrderedDictionary<string, JobParameter> myJobP = new OrderedDictionary<string, JobParameter> IDictionary<string, JobParameter> myJobP = new Dictionary<string, JobParameter> { {"p1", new JobParameter("param1")}, {"p2", new JobParameter(2)}, {"p3", new JobParameter(3.0)}, {"p4", new JobParameter(DateTime.Parse("1970-07-31"))} }; JobParameters jp = new JobParameters(myJobP); DefaultJobParametersConverter converter = new DefaultJobParametersConverter(); NameValueCollection props = converter.GetProperties(jp); Assert.IsNotNull(props); Assert.AreEqual(4,props.Count); foreach (string key in props.Keys) { string value = props[key]; Assert.IsNotNull(value); if (key.Contains("p1")) { Assert.AreEqual("p1", key); } if (key.Contains("p2")) { Assert.AreEqual("p2(long)", key); } if (key.Contains("p3")) { Assert.AreEqual("p3(double)", key); } if (key.Contains("p4")) { Assert.AreEqual("p4(date)", key); } } }
/// <summary> /// Use the same suffixes to create properties (omitting the string suffix /// because it is the default). Non-identifying parameters will be prefixed /// with the <see cref="NonIdentifyingFlag"/>. However, since parameters are /// identifying by default, they will <em>not</em> be prefixed with the /// <see cref="IdentifyingFlag"/>. /// </summary> /// <param name="parms"></param> /// <returns></returns> public NameValueCollection GetProperties(JobParameters parms) { if (parms == null || parms.IsEmpty()) { return new NameValueCollection(); } IDictionary<string, JobParameter> parameters = parms.GetParameters(); NameValueCollection result = new NameValueCollection(); foreach (KeyValuePair<string, JobParameter> entry in parameters) { string key = entry.Key; JobParameter jobParameter = entry.Value; Object value = jobParameter.Value; if (value != null) { key = (!jobParameter.Identifying ? NonIdentifyingFlag : "") + key; if (jobParameter.Type == JobParameter.ParameterType.Date) { result.Set(key + DateType, string.Format(_dateFormat, value)); } else if (jobParameter.Type == JobParameter.ParameterType.Long) { result.Set(key + LongType, string.Format(_numberFormat, value)); } else if (jobParameter.Type == JobParameter.ParameterType.Double) { result.Set(key + DoubleType, string.Format(_decimalFormat, (double)value)); } else { result.Set(key, "" + value); } } } return result; }
public void IsEmptyTest() { JobParameters jp = TearUp(); Assert.IsFalse(jp.IsEmpty()); JobParameters jp2 = new JobParameters(); Assert.IsTrue(jp2.IsEmpty()); }
/// <summary> /// Creates JobExecution. /// </summary> /// <param name="jobInstance"></param> /// <param name="jobParameters"></param> /// <param name="jobConfigurationLocation"></param> /// <returns></returns> public JobExecution CreateJobExecution(JobInstance jobInstance, JobParameters jobParameters, string jobConfigurationLocation) { Assert.NotNull(jobInstance, "A JobInstance is required to associate the JobExecution with"); Assert.NotNull(jobParameters, "A JobParameters object is required to create a JobExecution"); ExecutionContext executionContext = new ExecutionContext(); var jobExecution = new JobExecution(jobInstance, jobParameters, jobConfigurationLocation) { ExecutionContext = executionContext, LastUpdated = DateTime.Now }; // Save the JobExecution so that it picks up an ID (useful for clients // monitoring asynchronous executions): _jobExecutionDao.SaveJobExecution(jobExecution); _executionContextDao.SaveExecutionContext(jobExecution); return jobExecution; }
/// <summary> /// Increment the run.id parameter (starting with 1). /// </summary> /// <param name="parameters"></param> /// <returns></returns> public JobParameters GetNext(JobParameters parameters) { JobParameters parms = parameters ?? new JobParameters(); long id = parms.GetLong(_key, 0L) + 1; return new JobParametersBuilder(parms).AddLong(_key, id).ToJobParameters(); }
/// <summary> /// Custom constructor using a JobInstance, JobParameters and a Job configuration name. /// </summary> /// <param name="job"></param> /// <param name="jobParameters"></param> /// <param name="jobConfigurationName"></param> public JobExecution(JobInstance job, JobParameters jobParameters, string jobConfigurationName) : this(job, null, jobParameters, jobConfigurationName) { }
/// <summary> /// Custom constructor using an id, JobParameters and a job configuration name. /// </summary> /// <param name="id"></param> /// <param name="jobParameters"></param> /// <param name="jobConfigurationName"></param> public JobExecution(long id, JobParameters jobParameters, string jobConfigurationName) : this(null, id, jobParameters, jobConfigurationName) { }
public void GetHashCodeTest() { JobParameters jp = TearUp(); JobParameters jpCo = TearUp(); JobParameters jp2 = new JobParameters(); int hc = jp.GetHashCode(); int hcCo = jpCo.GetHashCode(); int hc2 = jp2.GetHashCode(); Assert.AreNotEqual(hc,hcCo); Assert.AreNotEqual(hc, hc2); }
public void Validate(JobParameters parameters) { //Do nothing on purpose }
/// <summary> /// Because a JobExecution isn't valid unless the job is set, this /// constructor is the only valid one from a modeling point of view. /// </summary> /// <param name="job"></param> /// <param name="id"></param> /// <param name="jobParameters"></param> /// <param name="jobConfigurationName"></param> public JobExecution(JobInstance job, long? id, JobParameters jobParameters, string jobConfigurationName) : base(id) { JobInstance = job; JobParameters = jobParameters ?? new JobParameters(); _jobConfigurationName = jobConfigurationName; }
/// <summary> /// Inserts job parameters into the job parameters table. /// </summary> /// <param name="executionId">the id of the job execution</param> /// <param name="jobParameters">job parameters to insert</param> private void InsertJobParameters(long? executionId, JobParameters jobParameters) { foreach (var pair in jobParameters) { var jobParameter = pair.Value; InsertParameter(executionId, jobParameter.Type, pair.Key, jobParameter.Value, jobParameter.Identifying); } }
/// <summary> /// Returns the last JobExecution. /// </summary> /// <param name="jobName"></param> /// <param name="jobParameters"></param> /// <returns></returns> public JobExecution GetLastJobExecution(string jobName, JobParameters jobParameters) { var jobInstance = _jobInstanceDao.GetJobInstance(jobName, jobParameters); if (jobInstance == null) { return null; } var jobExecution = _jobExecutionDao.GetLastJobExecution(jobInstance); if (jobExecution == null) { return null; } jobExecution.ExecutionContext = _executionContextDao.GetExecutionContext(jobExecution); _stepExecutionDao.AddStepExecutions(jobExecution); return jobExecution; }