/// <summary>Called to start the job.</summary> /// <param name="jobManager">Job manager</param> /// <param name="worker">Background worker</param> public void Run(JobManager jobManager, BackgroundWorker worker) { // Start the external process to run APSIM and wait for it to finish. Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = ApsimExecutable; if (!File.Exists(p.StartInfo.FileName)) throw new Exception("Cannot find executable: " + p.StartInfo.FileName); p.StartInfo.Arguments = StringUtilities.DQuote(fileName); p.StartInfo.WorkingDirectory = workingDirectory; p.StartInfo.CreateNoWindow = true; if (createSumFile) p.StartInfo.RedirectStandardOutput = true; p.Start(); if (createSumFile) { string sumFileName = Path.ChangeExtension(fileName, ".sum"); using (FileStream str = new FileStream(sumFileName, FileMode.Create)) { p.StandardOutput.BaseStream.CopyTo(str); } } p.WaitForExit(); }
public Boolean addSkillToJob(String JobId, String SkillId) { JobManager mgr = new JobManager(); JobDto obj = new JobDto(); obj.JobId = new Guid(JobId); return mgr.addSkillToJob(obj, SkillId); }
/// <summary>Processes any jobs that have been added.</summary> /// <param name="jobManager">The job manager.</param> private void ProcessAddedJobs(JobManager jobManager) { JobsService.Job runningJobDescription = null; //If there is no YP job running, then add a new job. Once a YP job is running don't add any more jobs (regardless of type). if (runningJob == null || jobManager.IsJobCompleted(runningJob)) { // Remove completed jobs if nothing is running. Otherwise, completedjobs will // grow and grow. jobManager.ClearCompletedJobs(); runningJob = null; using (JobsService.JobsClient jobsClient = new JobsService.JobsClient()) { runningJobDescription = jobsClient.GetNextToRun(); } if (runningJobDescription != null) { if (RunnableJobs.ProcessYPJob.IsF4PJob(runningJobDescription.Name) == true) runningJob = new RunnableJobs.ProcessF4PJob(true) { JobName = runningJobDescription.Name }; else runningJob = new RunnableJobs.ProcessYPJob(true) { JobName = runningJobDescription.Name }; if (runningJob != null) jobManager.AddJob(runningJob); } else { // No jobs to run so wait a bit. Thread.Sleep(15 * 1000); // 15 sec. } } }
public void CanEditAJobDefinition() { using (var session = EmbeddedRavenProvider.DocumentStore.OpenSession()) { var sut = new JobManager(session, DataServiceTestHelper.GetEventReporter().Object, new Mock<TypeLoader>().Object); string assemblyName = Guid.NewGuid().ToString(); string className = Guid.NewGuid().ToString(); string scheduleExpression = Guid.NewGuid().ToString(); string jobName = Guid.NewGuid().ToString(); var newJob = sut.CreateCronJob(jobName, Guid.NewGuid(), assemblyName, className, scheduleExpression); newJob.AssemblyName = Guid.NewGuid().ToString(); newJob.ClassName = Guid.NewGuid().ToString(); ((JobCronSchedule)newJob.Schedule).CronScheduleExpression = Guid.NewGuid().ToString(); newJob.JobName = Guid.NewGuid().ToString(); session.SaveChanges(); var dbItem = session.Load<JobDefinition>(newJob.Id); Assert.IsNotNull(dbItem); Assert.AreEqual(newJob.JobName, dbItem.JobName); session.Delete(dbItem); session.SaveChanges(); } }
/// <summary>Called to start the job.</summary> /// <param name="jobManager">The job manager running this job.</param> /// <param name="workerThread">The thread this job is running on.</param> public void Run(JobManager jobManager, BackgroundWorker workerThread) { // Call the all completed event in all models object[] args = new object[] { this, new EventArgs() }; foreach (Model childModel in Apsim.ChildrenRecursively(simulations)) Apsim.CallEventHandler(childModel, "AllCompleted", args); }
public void CanCreateASimpleJobDefinition() { using (var session = EmbeddedRavenProvider.DocumentStore.OpenSession()) { var sut = new JobManager(session, DataServiceTestHelper.GetEventReporter().Object, new Mock<TypeLoader>().Object); string assemblyName = Guid.NewGuid().ToString(); string className = Guid.NewGuid().ToString(); int intervalMinutes = 10; int delayStartMinutes = 20; string jobName = Guid.NewGuid().ToString(); var result = sut.CreateSimpleJob(jobName, Guid.NewGuid(), assemblyName, className, intervalMinutes, delayStartMinutes); Assert.IsNotNull(result); Assert.AreNotEqual(0, result.Id); var dbItem = session.Load<JobDefinition>(result.Id); Assert.IsNotNull(dbItem); Assert.AreEqual(jobName, dbItem.JobName); Assert.AreEqual(assemblyName, dbItem.AssemblyName); Assert.AreEqual(className, dbItem.ClassName); Assert.IsInstanceOf<JobSimpleSchedule>(dbItem.Schedule); Assert.AreEqual(intervalMinutes, ((JobSimpleSchedule)dbItem.Schedule).IntervalMinutes); Assert.AreEqual(delayStartMinutes, ((JobSimpleSchedule)dbItem.Schedule).DelayStartMinutes); session.Delete(dbItem); session.SaveChanges(); } }
public Boolean deleteJob(System.Guid JobId, String JobName, String CompensationId, System.Guid EmployerId, String JobDescription, int JobQuota, double JobExperienceLevel, double JobCompensationValue) { Job obj = Job.createJob(JobId, JobName, CompensationId, EmployerId, JobDescription, JobQuota, (decimal)JobExperienceLevel, (decimal)JobCompensationValue); JobManager mgr = new JobManager(); return mgr.deleteJob(obj); }
public Boolean deleteJob(Guid JobId, String JobName, String CompensationId, Guid EmployerId, String JobDescription, int JobQuota, double JobExperienceLevel, double JobCompensationValue) { JobManager mgr = new JobManager(); JobDto obj = mgr.createJobDTO(JobId, JobName, CompensationId, EmployerId, JobDescription, JobQuota, JobExperienceLevel, JobCompensationValue); return mgr.deleteJob(obj); }
/// <summary>Called to start the job.</summary> /// <param name="jobManager">The job manager running this job.</param> /// <param name="workerThread">The thread this job is running on.</param> public void Run(JobManager jobManager, BackgroundWorker workerThread) { // Extract the path from the filespec. If non specified then assume // current working directory. string path = Path.GetDirectoryName(fileSpec); if (path == null | path == "") path = Directory.GetCurrentDirectory(); List<string> files = Directory.GetFiles( path, Path.GetFileName(fileSpec), recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly).ToList(); // See above. FIXME! files.RemoveAll(s => s.Contains("UnitTests")); files.RemoveAll(s => s.Contains("UserInterface")); files.RemoveAll(s => s.Contains("ApsimNG")); // For each .apsimx file - read it in and create a job for each simulation it contains. string workingDirectory = Directory.GetCurrentDirectory(); string binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string apsimExe = Path.Combine(binDirectory, "Models.exe"); foreach (string apsimxFileName in files) { string arguments = StringUtilities.DQuote(apsimxFileName); if (runTests) arguments += " /RunTests"; jobManager.AddChildJob(this, new RunExternal(apsimExe, arguments, workingDirectory)); } }
/// <summary>Called to start the job.</summary> /// <param name="jobManager">The job manager running this job.</param> /// <param name="workerThread">The thread this job is running on.</param> public void Run(JobManager jobManager, BackgroundWorker workerThread) { // IF we are going to run all simulations, we can delete all tables in the DataStore. This // will clean up order of columns in the tables and removed unused ones. // Otherwise just remove the unwanted simulations from the DataStore. DataStore store = Apsim.Child(simulations, typeof(DataStore)) as DataStore; if (model is Simulations) store.DeleteAllTables(); else store.RemoveUnwantedSimulations(simulations); store.Disconnect(); JobSequence parentJob = new JobSequence(); JobParallel simulationJobs = new JobParallel(); FindAllSimulationsToRun(model, simulationJobs); parentJob.Jobs.Add(simulationJobs); parentJob.Jobs.Add(new RunAllCompletedEvent(simulations)); if (runTests) { foreach (Tests tests in Apsim.ChildrenRecursively(model, typeof(Tests))) parentJob.Jobs.Add(tests); } jobManager.AddChildJob(this, parentJob); }
/// <summary>Constructor</summary> /// <param name="job">The job to run.</param> /// <param name="name">The name of the job</param> /// <param name="presenter">The explorer presenter.</param> public RunCommand(JobManager.IRunnable job, string name, ExplorerPresenter presenter) { this.job = job; this.jobName = name; this.explorerPresenter = presenter; jobManager = new JobManager(); }
public Boolean addSkillToJob(System.Guid JobId, String SkillId) { JobManager mgr = new JobManager(); Job job = new Job(); job.JobId = JobId; Job obj = mgr.selectJobById(job); return mgr.addSkillToJob(obj, SkillId); }
/// <summary>Constructor</summary> /// <param name="job">The job to run.</param> /// <param name="name">The name of the job</param> /// <param name="presenter">The explorer presenter.</param> public RunCommand(List<JobManager.IRunnable> jobs, string name, ExplorerPresenter presenter) { this.jobs = jobs; this.jobName = name; this.explorerPresenter = presenter; jobManager = new JobManager(); }
/// <summary> /// Constructor /// </summary> /// <param name="simulations">The top level simulations object.</param> /// <param name="simulation">The simulation object clicked on.</param> /// <param name="presenter">The explorer presenter.</param> public RunCommand(Simulations simulations, Model simulation, ExplorerPresenter presenter) { this.simulations = simulations; this.modelClicked = simulation; this.explorerPresenter = presenter; jobManager = new JobManager(); jobManager.AllJobsCompleted += OnComplete; }
protected override void OnStart(string[] args) { if (jobManager == null) { jobManager = new JobManager(maximumNumberOfProcessors); jobManager.AddJob(new RunJobsInDB()); } jobManager.Start(waitUntilFinished: false); }
/// <summary>Constructor</summary> /// <param name="job">The job to run.</param> /// <param name="name">The name of the job</param> /// <param name="presenter">The explorer presenter.</param> public RunCommand(JobManager.IRunnable job, string name, ExplorerPresenter presenter) { jobs = new List<JobManager.IRunnable>(); this.jobs.Add(job); this.jobName = name; this.explorerPresenter = presenter; jobManager = new JobManager(); }
/// <summary>Called to start the job.</summary> /// <param name="jobManager">The job manager running this job.</param> /// <param name="workerThread">The thread this job is running on.</param> public void Run(JobManager jobManager, BackgroundWorker workerThread) { // Call the all completed event in all models object[] args = new object[] { this, new EventArgs() }; Events events = new Events(); events.AddModelEvents(simulations); events.CallEventHandler(simulations, "AllCompleted", args); }
protected override void Awake() { base.Awake(); _inputHelper = GameInputHelper.Instance; _inputMgr = InputManager.Instance; _jobMgr = JobManager.Instance; System = gameObject.GetSingleComponentInParents<SystemItem>(); D.AssertEqual(Layers.SystemOrbitalPlane, (Layers)gameObject.layer, ((Layers)gameObject.layer).GetValueName()); Subscribe(); }
/// <summary>Called when the form is loaded</summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void OnLoad(object sender, EventArgs e) { int maximumNumberOfCores = -1; if (arguments.ContainsKey("-MaximumNumberOfCores")) maximumNumberOfCores = Convert.ToInt32(arguments["-MaximumNumberOfCores"]); jobManager = new JobManager(maximumNumberOfCores); jobManager.AddJob(new RunJobsInDB()); jobManager.Start(waitUntilFinished: false); }
/// <summary>Constructor</summary> /// <param name="job">The job to run.</param> /// <param name="name">The name of the job</param> /// <param name="presenter">The explorer presenter.</param> /// <param name="multiProcess">Use the multi-process runner?</param> public RunCommand(List<JobManager.IRunnable> jobs, string name, ExplorerPresenter presenter, bool multiProcess) { this.jobs = jobs; this.jobName = name; this.explorerPresenter = presenter; if (multiProcess) jobManager = new JobManagerMultiProcess(); else jobManager = new JobManager(); }
/// <summary>Called to start the job.</summary> /// <param name="jobManager">The job manager running this job.</param> /// <param name="workerThread">The thread this job is running on.</param> public void Run(JobManager jobManager, BackgroundWorker workerThread) { Simulation clonedSim = Apsim.Clone(simulation) as Simulation; Simulations simulations = Apsim.Parent(simulation, typeof(Simulations)) as Simulations; simulation.FileName = simulations.FileName; Simulations.MakeSubstitutions(simulations, new List<Simulation> { clonedSim }); Simulations.CallOnLoaded(clonedSim); jobManager.AddChildJob(this, clonedSim); }
/// <summary>Called to start the job.</summary> /// <param name="jobManager">Job manager</param> /// <param name="worker">Background worker</param> public void Run(JobManager jobManager, BackgroundWorker worker) { // Sort out the command arguments. string args = Path.GetFileName(fileName); if (arguments != null) args += " " + arguments; // Open the summary file for writing. summaryFile = new StreamWriter(Path.ChangeExtension(fileName, ".sum")); string binDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string ausfarmBin = Path.Combine(binDirectory, "AusFarm"); // Copy in the .prm files. foreach (string prmFileName in Directory.GetFiles(ausfarmBin, "*.prm")) { File.Copy(prmFileName, Path.Combine(workingDirectory, Path.GetFileName(prmFileName))); } // Start the external process to run AusFarm and wait for it to finish. Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = Path.Combine(ausfarmBin, "auscmd32.exe"); p.StartInfo.Arguments = args; p.StartInfo.WorkingDirectory = workingDirectory; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += OnStdOutWrite; p.EnableRaisingEvents = true; p.Start(); p.BeginOutputReadLine(); string StdErr = p.StandardError.ReadToEnd(); p.WaitForExit(); // Close the summary file. summaryFile.Close(); // Look for an error log file. Seems the error file gets written to the AusFarm // directory rather than the same place as the .sdml. // If found then copy into the working directory. string errorFile = Path.Combine(binDirectory, "AusFarm", Path.GetFileName(fileName) + "_errors.log"); if (File.Exists(errorFile)) { File.Move(errorFile, Path.Combine(workingDirectory, Path.GetFileName(errorFile))); } // Do post simulation stuff. DoPostSimulation(); }
private static JobManager CreateJobWorkersManager() { var jobs = new IJob[] { new SampleJob(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(20)), /* new ExceptionJob(TimeSpan.FromSeconds(15)), */ new WorkItemCleanupJob(TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5), new WorkItemsContext()) }; var coordinator = new WebFarmJobCoordinator(new EntityWorkItemRepository(() => new WorkItemsContext())); var manager = new JobManager(jobs, coordinator); manager.Fail(ex => Elmah.ErrorLog.GetDefault(null).Log(new Error(ex))); return manager; }
public async Task GivenNotStarted_WhenQueue_ThenIgnore() { var data = "test"; job.Object.ProcessThrows = false; ExpectJobFactoryToCreateJob(data); var sut = new JobManager<string>(jobFactory.Object); sut.QueueJob(data); await sut.CompleteAsync(); job.Verify(x => x.ProcessAsync(It.IsAny<CancellationToken>()), Times.Never); }
public void ExecuteJob(string JobKey, string Group) { try { JobManager jm = new JobManager(); Diagnostics.Log.Info(String.Format("Job {0} was executed at {1} on demand by {2}", JobKey, DateTime.Now, Context.User.Name), this); jm.ExecuteJob(JobKey, Group); } catch(Exception ex) { Diagnostics.Log.Error(String.Format("Sitecore.QuartzScheuler: Sitecore.QuartzScheuler: Error occured while exedcuting job {0} at {1} on demand by {2}", JobKey, DateTime.Now, Context.User.Name), this); Diagnostics.Log.Error("Sitecore.QuartzScheuler: " + ex.Message + Environment.NewLine + ex.StackTrace, this); throw ex; } }
public void GetsTheJobDone() { var jobDoneEvent = new ManualResetEvent(false); var job = new Mock<IJob>(); job.Setup(j => j.Interval).Returns(TimeSpan.FromMilliseconds(1)); var jobs = new[] { job.Object }; var coordinator = new Mock<IJobCoordinator>(); coordinator.Setup(c => c.GetWork(job.Object)).Returns(new Task(() => jobDoneEvent.Set())); using (var manager = new JobManager(jobs, coordinator.Object)) { manager.Start(); Assert.True(jobDoneEvent.WaitOne(TimeSpan.FromSeconds(2))); } }
/// <summary> /// Same method is called in ItemSaved and ItemDeleted pipeline based on the configuration /// </summary> /// <param name="sender">An item on which the event has occured</param> /// <param name="args">Event arguments</param> public void OnItemChanged(object sender, EventArgs args) { Item changedItem = Event.ExtractParameter(args, 0) as Item; if (changedItem != null && changedItem.Database.Name.ToLower() == "master") { //Check for all the templates used for QuartzScheduler if (changedItem.TemplateID == ID.Parse("{822F8EF2-16CE-4B31-AD36-4F2132D81A39}") || changedItem.TemplateID == ID.Parse("{C57D9C9A-BA63-4C3E-BFD5-4823B20BB5AE}") ) { JobManager scheduler = new JobManager(); scheduler.ScheduleJobs(); } } }
public async Task GivenCompleted_WhenQueueJob_ThenThrow() { var data = "test"; job.Object.ProcessThrows = false; ExpectJobFactoryToCreateJob(data); var sut = new JobManager<string>(jobFactory.Object); sut.Start(); await sut.CompleteAsync(); sut.QueueJob(data); }
/// <summary>Called to start the job.</summary> /// <param name="jobManager">Job manager</param> /// <param name="worker">Background worker</param> public void Run(JobManager jobManager, BackgroundWorker worker) { while (!worker.CancellationPending) { try { // Process that have been added. ProcessAddedJobs(jobManager); Thread.Sleep(1000); // 1 seconds } catch (Exception err) { WriteToLog(err.Message); } } }
public ActionResult GetJobFireTimes() { var returnValue = new JsonResult(); returnValue.JsonRequestBehavior = JsonRequestBehavior.AllowGet; try { JobManager jm = new JobManager(); var currentJobList = jm.GetJobFireTimes(); returnValue.Data = HelperUtility.GetJsonSerializedData(currentJobList, false); } catch (Exception ex) { Diagnostics.Log.Error("Sitecore.QuartzScheuler: Error in GetJobFireTimes : " + ex.Message + Environment.NewLine + ex.StackTrace, this); throw ex; } return returnValue; }
private void AddUserJobs(SocketGuildUser user) { JobManager.AddJob(async() => await UserTimeOut(user), s => s .WithName($"[FBQ_UserTimeOut_{user.Id}]").ToRunOnceAt(DateTime.Now.Add(_timeLeft))); }
public void Schedule() { JobManager.AddJob(this, s => s.WithName(nameof(GetWinnerEverydayJob)).ToRunEvery(0).Days().At(12, 00)); }
public void Initialize() => JobManager.AddJob(async() => await PostAllServerInfoAsync().ConfigureAwait(false), (x) => x.ToRunNow().AndEvery(1).Minutes());
public ActionResult RunImport(string id, string db, string importType) { var currentDB = (!string.IsNullOrWhiteSpace(db)) ? Configuration.Factory.GetDatabase(db) : Context.ContentDatabase; Item importItem = null; if (ID.IsID(id)) { importItem = currentDB.GetItem(ID.Parse(id)); } //check import item if (importItem == null) { return(GetResult("", "Import item is null")); } //check handler assembly TextField ha = importItem.Fields["Handler Assembly"]; if (ha == null || string.IsNullOrWhiteSpace(ha.Value)) { return(GetResult("", "Import handler assembly is not defined")); } //check handler class TextField hc = importItem.Fields["Handler Class"]; if (hc == null || string.IsNullOrWhiteSpace(hc.Value)) { return(GetResult("", "Import handler class is not defined")); } //check db if (currentDB == null) { return(GetResult("", "Database is null")); } //check conn str Field connStrField = importItem.Fields["Connection String Name"]; if (connStrField == null) { return(GetResult("", "Connection String Name is not set")); } var connStr = ""; var connName = connStrField.Value; if (string.IsNullOrWhiteSpace(connName)) { return(GetResult("", "Connection String Name is empty")); } foreach (ConnectionStringSettings c in ConfigurationManager.ConnectionStrings) { if (!c.Name.ToLower().Equals(connName.ToLower())) { continue; } connStr = c.ConnectionString; break; } if (string.IsNullOrWhiteSpace(connStr)) { return(GetResult("", "Connection string is empty")); } //try to instantiate object IDataMap map = null; ILogger l = new DefaultLogger(); try { map = (IDataMap)Reflection.ReflectionUtil.CreateObject( ha.Value, hc.Value, new object[] { currentDB, connStr, importItem, l } ); } catch (FileNotFoundException fnfe) { var n = fnfe.Message; return(GetResult("", $"the binary {ha.Value} could not be found")); } //run process if (map == null) { var dbName = currentDB?.Name; var importItemName = importItem?.Name; var loggerType = l.GetType().ToString(); return(GetResult("", $"the data map provided could not be instantiated. Database:{dbName}, Connection String: {connStr}, Import Item: {importItemName}, Logger: {loggerType}")); } string handleName = $"{importType}Import-{DateTime.UtcNow:yyyy/MM/dd-hh:mm}"; var importService = new ImportProcessor(map, l); var jobOptions = new DefaultJobOptions( handleName, importItem.DisplayName, Context.Site.Name, importService, "Process", new object[] { }); JobManager.Start(jobOptions); return(GetResult(handleName, "")); }
private void Initialize() { ConnectCommand = new RelayCommand(UpdateGameServer, CanConnectGameServer); GetData(); JobManager.Initialize(new Registry()); }
public void HandlePullTheHandleForPolice(GameClients.GameClient Session, RoomItem Item, int Request, bool HasRights) { RoomUser User = Item.GetRoom().GetRoomUserManager().GetRoomUserByHabbo(Session.GetHabbo().Id); if (Item.InteractingUser2 != User.UserId) { Item.InteractingUser2 = User.UserId; } if (User == null) { return; } if (User.Coordinate != Item.SquareInFront && User.CanWalk) { User.MoveTo(Item.SquareInFront); return; } if (!Session.GetRoleplay().MultiCoolDown.ContainsKey("rp_vswitch")) { Session.GetRoleplay().MultiCoolDown.Add("rp_vswitch", 0); } if (Session.GetRoleplay().MultiCoolDown["rp_vswitch"] > 0) { Session.SendWhisperBubble("You must wait until you can pull the switch! [" + Session.GetRoleplay().MultiCoolDown["rp_vswitch"] + "/15]", 1); return; } lock (Plus.GetGame().GetClientManager().Clients.Values) { foreach (GameClient client in Plus.GetGame().GetClientManager().Clients.Values) { if (client == null) { continue; } if (client.GetRoleplay() == null) { continue; } if (!JobManager.validJob(client.GetRoleplay().JobId, client.GetRoleplay().JobRank)) { continue; } if (!client.GetRoleplay().JobHasRights("police")) { continue; } if (!client.GetRoleplay().JobHasRights("swat")) { continue; } if (!client.GetRoleplay().Working) { continue; } string msg = Session.GetHabbo().UserName + " has pulled the switch at [Room ID: " + Session.GetHabbo().CurrentRoomId + "], asking for help!"; Radio.send(msg, Session); } } RoleplayManager.Shout(Session, "*Pulls the trigger of the switch, notifying the cops*", 4); Session.GetRoleplay().MultiCoolDown["rp_vswitch"] = 15; Session.GetRoleplay().CheckingMultiCooldown = true; }
} // ProcessRecord #endregion Overrides #region Protected Members /// <summary> /// Helper method to find jobs based on parameter set. /// </summary> /// <returns>Matching jobs</returns> protected List <Job> FindJobs() { List <Job> jobList = new List <Job>(); switch (ParameterSetName) { case NameParameterSet: { jobList.AddRange(FindJobsMatchingByName(true, false, true, false)); } break; case InstanceIdParameterSet: { jobList.AddRange(FindJobsMatchingByInstanceId(true, false, true, false)); } break; case SessionIdParameterSet: { if (Id != null) { jobList.AddRange(FindJobsMatchingBySessionId(true, false, true, false)); } else { // Get-Job with no filter. jobList.AddRange(JobRepository.Jobs); jobList.AddRange(JobManager.GetJobs(this, true, false, null)); } } break; case CommandParameterSet: { jobList.AddRange(FindJobsMatchingByCommand(false)); } break; case StateParameterSet: { jobList.AddRange(FindJobsMatchingByState(false)); } break; case FilterParameterSet: { jobList.AddRange(FindJobsMatchingByFilter(false)); } break; default: break; } jobList.AddRange(FindChildJobs(jobList)); jobList = ApplyHasMoreDataFiltering(jobList); return(ApplyTimeFiltering(jobList)); }
private void Application_Start(object sender, EventArgs e) { // Code that runs on application startup RegisterRoutes(RouteTable.Routes); JobManager.Initialize(new FrameworkLibrary.Classes.JobSchedulerRegistry()); }
protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); JobManager.Initialize(new JobRegistry()); }
public void Initialize() { if (!DataSetFactory.ContainsProvider("memory")) { DataSetFactory.Register(typeof(MemoryDataSet)); } if (!DataSetFactory.ContainsProvider("ab")) { DataSetFactory.Register(typeof(AzureBlobDataSet)); } string customTempLocalResourcePath = RoleEnvironment.GetLocalResource("localStorage1").RootPath; Environment.SetEnvironmentVariable("TMP", customTempLocalResourcePath); Environment.SetEnvironmentVariable("TEMP", customTempLocalResourcePath); string jobsDatabaseConnectionString = RoleEnvironment.GetConfigurationSettingValue("FetchClimate.JobsDatabaseConnectionString"); string jobsStorageConnectionString = RoleEnvironment.GetConfigurationSettingValue("FetchClimate.JobsStorageConnectionString"); foreach (TraceListener item in Trace.Listeners) { if (!(item is DefaultTraceListener)) // The default trace listener is always in any TraceSource.Listeners collection. { AutoRegistratingTraceSource.RegisterTraceListener(item); WorkerTrace.TraceEvent(TraceEventType.Information, 19, string.Format("TraceListener \"{0}\" registered for accepting data from all AutoRegistratingTraceSources", item.ToString())); } } JobManager.InitializeJobTable(jobsDatabaseConnectionString, false); configProvider = new SqlExtendedConfigurationProvider( RoleEnvironment.GetConfigurationSettingValue("ConfigurationDatabaseConnectionString")); WorkerTrace.TraceEvent(TraceEventType.Information, 6, string.Format("Connected to configuration database. Latest timestamp {0}", configProvider.GetConfiguration(DateTime.MaxValue).TimeStamp)); azureGAC = new AssemblyStore(RoleEnvironment.GetConfigurationSettingValue("FetchWorker.AssemblyStoreConnectionString")); //overriding bug-containing default azure provider with the fixed one Type t = typeof(DataSetFactory); var dict = (System.Collections.IDictionary)t.InvokeMember("providersByName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetField, null, null, null); dict.Remove("az"); DataSetFactory.Register(typeof(Microsoft.Research.Science.Data.Azure.AzureDataSet)); WorkerTrace.TraceEvent(TraceEventType.Verbose, 9, "Available Scientific DataSet providers:\n" + DataSetFactory.RegisteredToString()); if (int.TryParse(RoleEnvironment.GetConfigurationSettingValue("JobTouchPeriod"), out touchPeriodInSeconds)) { WorkerTrace.TraceEvent(TraceEventType.Verbose, 10, string.Format("Touch period for processing job is set to {0}", touchPeriodInSeconds)); } else { WorkerTrace.TraceEvent(TraceEventType.Warning, 11, string.Format("Failed to read touch period from config. Parsing of value failed. touch period is set to {0}", touchPeriodInSeconds)); } manager = new JobManager(jobsDatabaseConnectionString, jobsStorageConnectionString); //Scheduling cleanup string instanceId = RoleEnvironment.CurrentRoleInstance.Id; int.TryParse(instanceId.Substring(instanceId.LastIndexOf(".") + 1), out instanceIndex); if (instanceIndex == 0) { double cleanPeriod = 0; if (!double.TryParse(RoleEnvironment.GetConfigurationSettingValue("HoursBetweenCleanup"), out cleanPeriod)) { cleanPeriod = 23; WorkerTrace.TraceEvent(TraceEventType.Warning, 12, "Failed to parse period between clean-ups from configuration. Setting it to default 23 hours."); } cleanupTimeSpan = TimeSpan.FromHours(cleanPeriod); lastCleanUpTime = manager.LastCleanUpTime; DateTime now = DateTime.UtcNow; if (now - lastCleanUpTime >= cleanupTimeSpan) { manager.SubmitCleanUp(); lastCleanUpTime = now; } } WorkerTrace.TraceEvent(TraceEventType.Verbose, 13, string.Format("starting Allocated memory: {0}Mb", GC.GetTotalMemory(false) / 1024 / 1024)); }
public JobDetail FindById(string id) { var jobManager = new JobManager(); return(jobManager.GetJobDetails(id)); }
static Core() { RuntimeSpanCounter = new Stopwatch(); JobManager.Initialize(); }
private void RemoveUserJobs(ulong userId) { JobManager.RemoveJob($"[FBQ_UserTimeOut_{userId}]"); }
public void InitializeJobs() { JobManager.Initialize(new ScheduledJobRegistry()); }
public JobsModel(JobManager jobMgr) { this._jobMgr = jobMgr; }
/// <summary> /// This will take the basic data provided about the account, upload the necessary information to the account, and schedule a job. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnStart_Click(object sender, RoutedEventArgs e) { BatchCredentials credentials = new BatchCredentials(txtBAccountName.Text, txtBAccountKey.Text); IBatchClient bClient = BatchClient.Connect(SampleConstants.BatchSvcEndpoint, credentials); // Setting a retry policy adds robustness against an individual call timing out. When using a policy, by default all recoverable failures are retried. bClient.CustomBehaviors.Add(new SetRetryPolicy(new ExponentialRetry(TimeSpan.FromSeconds(5), 5))); // Create a unique workitem name; don't forget to delete these when you're done string workItemName = SampleConstants.WorkItemNamePrefix + Guid.NewGuid().ToString(); // Identify the pre-existing pool of VMs that will run the tasks. An Autopool specification // is fine but there is the delay associated with the creation of the pool along with waiting // for the VMs to reach Idle state before tasks are running. You can use Batch Explorer to // pre-create the pool and then resize it to the desired size and number of VMs. JobExecutionEnvironment jee = new JobExecutionEnvironment() { PoolName = PoolName }; // Next, create the JobManager instance describing the environment settings and resources it // needs to run JobManager jobMgr = new JobManager() { Name = "JM1", CommandLine = SampleConstants.JobManager, // NOTE: We do not in general recommend that customers put their secrets on the command line or as environmental variables, as // these are not a secure locations. This was done for the simplicity of the sample. EnvironmentSettings = new List <IEnvironmentSetting>() { { new EnvironmentSetting(SampleConstants.EnvWorkItemName, workItemName) }, { new EnvironmentSetting(SampleConstants.EnvBatchAccountKeyName, txtBAccountKey.Text) } }, // In many cases you will want KillJobOnCompletion to be set to 'TRUE' - this allows the previous job to finish before // a recurrence is scheduled. As an alternative, you can set this to 'FALSE' and use MaxWallClockTime as shown below, // which will instead ensure that every recurrence happens. KillJobOnCompletion = true }; // Create a list of resource files that are needed to run JobManager.exe. A shared access signature key specifying // readonly access is used so the JobManager program will have access to the resource files when it is started // on a VM. var sasPrefix = Helpers.ConstructContainerSas( txtSAccountName.Text, txtSAccountKey.Text, "core.windows.net", txtSContainerName.Text); jobMgr.ResourceFiles = Helpers.GetResourceFiles(sasPrefix, SampleConstants.JobManagerFiles); // Create the job specification, identifying that this job has a job manager associated with it JobSpecification jobSpec = new JobSpecification() { JobManager = jobMgr }; // Set up the desired recurrence or start time schedule. WorkItemSchedule wiSchedule = new WorkItemSchedule(); if (rdoOnce.IsChecked == true) { // Set information if the task is to be run once. DateTime runOnce = (DateTime)(dpkDate.SelectedDate); runOnce = runOnce.AddHours(cbxHourO.SelectedIndex); runOnce = runOnce.AddMinutes(cbxMinuteO.SelectedIndex); wiSchedule.DoNotRunUntil = runOnce; } else { // Set information if the task is to be recurring. TimeSpan recurring = new TimeSpan(cbxHourR.SelectedIndex, cbxMinuteR.SelectedIndex, 0); wiSchedule.RecurrenceInterval = recurring; TimeSpan countback = new TimeSpan(0, 0, 30); jobSpec.JobConstraints = new JobConstraints(recurring.Subtract(countback), null); } // Upload files and create workitem. UploadFiles(); using (IWorkItemManager wiMgr = bClient.OpenWorkItemManager()) { ICloudWorkItem workItem = wiMgr.CreateWorkItem(workItemName); workItem.JobExecutionEnvironment = jee; workItem.Schedule = wiSchedule; workItem.JobSpecification = jobSpec; try { workItem.Commit(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } // Remember to clean up your workitems and jobs }
/// <summary> /// Posts a new announcement message and alerts playtester role /// </summary> /// <returns></returns> public async Task PlaytestStartingInTask() { if (_data.RSettings.ProgramSettings.Debug) { _ = _log.LogMessage("Posting playtest announcement", false, color: LOG_COLOR); } //Start asking the server for player counts. _data.IncludePlayerCount = true; //Start asking for player counts JobManager.AddJob(async() => await _data.GetPlayCountFromServer(_data.GetServerCode(_calendar.GetTestEventNoUpdate().ServerLocation)), s => s.WithName("[QueryPlayerCount]").ToRunEvery(60).Seconds()); //Prevent new server reservations. CanReserveServers = false; //Figure out how long until the event starts var countdown = _calendar.GetTestEventNoUpdate().StartDateTime.GetValueOrDefault().Subtract(DateTime.Now); var countdownString = countdown.ToString("d'D 'h' Hour 'm' Minutes'").TrimStart(' ', 'D', 'H', 'o', 'u', 'r', '0').Replace(" 0 Minutes", ""); var mentionRole = _data.PlayTesterRole; string unsubInfo = ""; //DM users about their test foreach (var creator in _calendar.GetTestEventNoUpdate().Creators) { try { await creator.SendMessageAsync($"Don't forget that you have a playtest for __**{_calendar.GetTestEventNoUpdate().Title}**__ in __**{countdownString}**__"); } catch { //Could not DM creator about their test. } } //Handle comp or casual if (_calendar.GetTestEvent().IsCasual) { await _data.RconCommand(_calendar.GetTestEventNoUpdate().ServerLocation, $"sv_password {_data.RSettings.General.CasualPassword}"); unsubInfo = "\nType `>playtester` to stop getting these notifications."; } else { await _data.RconCommand(_calendar.GetTestEventNoUpdate().ServerLocation, $"sv_password {_calendar.GetTestEventNoUpdate().CompPassword}"); mentionRole = _data.CompetitiveTesterRole; } await mentionRole.ModifyAsync(x => { x.Mentionable = true; }); await _data.TestingChannel.SendMessageAsync($"Heads up {mentionRole.Mention}! " + $"There is a playtest starting in {countdownString}." + $"{unsubInfo}", embed : _announcementMessage.CreatePlaytestEmbed(_calendar.GetTestEventNoUpdate().IsCasual, true, PlaytestAnnouncementMessage.Id)); await mentionRole.ModifyAsync(x => { x.Mentionable = false; }); await _data.CompetitiveTestingChannel.SendMessageAsync($"**{_calendar.GetTestEventNoUpdate().Title}** Paste the following into console to join:" + $"```connect {_calendar.GetTestEventNoUpdate().ServerLocation}; password {_calendar.GetTestEventNoUpdate().CompPassword}```"); }
// if you are using jobs, you need this public override void PerformFetch(UIApplication application, Action <UIBackgroundFetchResult> completionHandler) => JobManager.OnBackgroundFetch(completionHandler);
public object PollCommandOutput(string guid, string handle, string stringFormat) { if (!IsLoggedInUserAuthorized) { return(string.Empty); } HttpContext.Current.Response.ContentType = "application/json"; var serializer = new JavaScriptSerializer(); var session = GetScriptSession(guid); var result = new Result(); var scriptJob = JobManager.GetJob(GetJobId(guid, handle)); if (scriptJob == null) { result.status = StatusError; result.result = "Can't find your command result. This might mean that your job has timed out or your script caused the application to restart."; result.prompt = $"PS {session.CurrentLocation}>"; if (!session.Output.HasUpdates()) { session.Output.Clear(); return(serializer.Serialize(result)); } } else { result.handle = handle; } if (scriptJob != null && scriptJob.Status.Failed) { result.status = StatusError; var message = string.Join(Environment.NewLine, scriptJob.Status.Messages.Cast <string>().ToArray()) .Replace("[", "[") .Replace("]", "]"); result.result = "[[;#f00;#000]" + (message.IsNullOrEmpty() ? "Command failed" : HttpUtility.HtmlEncode(message)) + "]"; result.prompt = $"PS {session.CurrentLocation}>"; session.Output.Clear(); return(serializer.Serialize(result)); } var complete = scriptJob == null || scriptJob.IsDone; var output = new StringBuilder(); session.Output.GetConsoleUpdate(output, 131072); var partial = session.Output.HasUpdates(); result.result = output.ToString().TrimEnd('\r', '\n'); result.prompt = $"PS {session.CurrentLocation}>"; result.status = complete ? (partial ? StatusPartial : StatusComplete) : StatusWorking; result.background = OutputLine.ProcessHtmlColor(session.PrivateData.BackgroundColor); result.color = OutputLine.ProcessHtmlColor(session.PrivateData.ForegroundColor); if (partial && complete) { session.Output.Clear(); } var serializedResult = serializer.Serialize(result); return(serializedResult); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { /*ef*/ services.AddDbContext <EfDbContext>(option => option.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));//配置sqlserver //services.AddScoped<IUnitOfWork, UnitOfWork<EfDbContext>>();//注入UOW依赖,确保每次请求都是同一个对象 //依赖注入 若出现重复注册的问题,请使用AddTransient //services.AddTransient<IDatabaseFactory, DatabaseFactory>(); /*注入httpContext*/ services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <IConfigurationRoot>(Configuration); /*跨域访问*/ #region 跨域 var urls = Configuration.GetSection("CoresSettings:Urls").Value.Split(','); services.AddCors(options => options.AddPolicy("CoresDomain", blder => blder.WithOrigins(urls) .AllowAnyMethod() .AllowAnyHeader() .AllowAnyOrigin() .AllowCredentials()) ); #endregion 跨域 //identityServer4 services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = Configuration.GetSection("IdentityServerSettings:Authority").Value; options.RequireHttpsMetadata = false; options.ApiName = Configuration.GetSection("IdentityServerSettings:ApiName").Value; }); /*https://www.cnblogs.com/daxnet/p/6181366.html*/ //Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "Netcore.Api接口文档", Description = "RESTful API for Netcore.Api", TermsOfService = "None", Contact = new Contact { Name = "Alvin_Su", Email = "*****@*****.**", Url = "" } }); //Set the comments path for the swagger json and ui. var basePath = PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = Path.Combine(basePath, "WechatBusiness.Api.xml"); c.IncludeXmlComments(xmlPath); c.DescribeAllEnumsAsStrings(); c.IgnoreObsoleteActions(); //identityServer4 c.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "password", //AuthorizationUrl = "http://localhost:5006", TokenUrl = string.Concat(Configuration.GetSection("IdentityServerSettings:Authority").Value.TrimEnd('/') , Configuration.GetSection("IdentityServerSettings:TokenUrl").Value),// "http://auth.handnear.com/connect/token", Scopes = new Dictionary <string, string> { { "Api", "secret" } }, }); c.OperationFilter <HttpHeaderOperation>(); // 添加httpHeader参数 }); //Hangfire services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection"))); //Area var baseController = typeof(BaseController); var controllerAssembly = baseController.GetTypeInfo().Assembly; services.AddMvc(options => { //options.Filters.Add<ApiResourceFilter>(); options.Filters.Add <ApiExceptionFilter>(); options.Filters.Add <ApiActionFilter>(); options.Filters.Add(new ApiAuthorizationFilter()); //支持原始输入 options.InputFormatters.Insert(0, new RawRequestBodyFormatter()); //xml //options.ReturnHttpNotAcceptable = true; //options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>(); //options.InputFormatters.Add(new XmlSerializerInputFormatter()); //options.OutputFormatters.Add(new XmlSerializerOutputFormatter()); //options.Conventions.Add(new CommandParameterBindingConvention()); }).ConfigureApplicationPartManager(m => { var feature = new ControllerFeature(); m.ApplicationParts.Add(new AssemblyPart(controllerAssembly)); m.PopulateFeature(feature); services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray()); }).AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; //默认返回json为小写,设置后不会变换model字段的大小写 options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //automapper services.AddAutoMapper(typeof(IProfile)); //redis var redisAppSet = Configuration.GetSection("RedisSettings").Get <RedisSettings>(); if (redisAppSet.IsEnabled) { var redisOption = new RedisCacheOptions() { Configuration = redisAppSet.Connection, InstanceName = redisAppSet.InstanceName }; services.AddSingleton <ICacheHelper>(new RedisCacheHelper(redisOption, redisAppSet.Database ?? 0)); } else//MemoryCache { services.AddSingleton <ICacheHelper>(new MemoryCacheHelper(new MemoryCacheOptions())); } //RabbitMQ var rabbitMQAppSet = Configuration.GetSection("RabbitMQSettings").Get <RabbitMQSetting>(); if (rabbitMQAppSet.IsEnabled) { services.AddSingleton(new RabbitMQHelper(rabbitMQAppSet)); } //autofac var builder = new ContainerBuilder(); //builder.RegisterType<AccountService>().As<IAccountService>(); //builder.RegisterGeneric(typeof(EfRepositoryBase<>)).As(typeof(IRepository<>)).InstancePerDependency();//注册仓储泛型 builder.Populate(services); var module = new ConfigurationModule(Configuration); builder.Register(c => new AopInterceptor()); builder.RegisterModule(module); this.Container = builder.Build(); //FluentScheduler --Hangfire JobManager.Initialize(new TaskBaseRegistry()); JobManager.Stop(); return(new AutofacServiceProvider(this.Container));; }
public SchedulerController(JobManager jobManager) { _jobManager = jobManager; }
public IJob GetJob(string jobName) { var job = JobManager.GetJob(jobName); return(job == null ? null : new SpeJob(job)); }
/// <summary> /// The expression will be executed in the remote computer if a /// remote runspace parameter or computer name is specified. If /// none other than command parameter is specified, then it /// just executes the command locally without creating a new /// remote runspace object. /// </summary> protected override void ProcessRecord() { if (ParameterSetName == DefinitionNameParameterSet) { // Get the Job2 object from the Job Manager for this definition name and start the job. string resolvedPath = null; if (!string.IsNullOrEmpty(_definitionPath)) { ProviderInfo provider = null; System.Collections.ObjectModel.Collection <string> paths = this.Context.SessionState.Path.GetResolvedProviderPathFromPSPath(_definitionPath, out provider); // Only file system paths are allowed. if (!provider.NameEquals(this.Context.ProviderNames.FileSystem)) { string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotFSProvider, _definitionName, _definitionPath, provider.FullName); WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotFileSystemProvider", ErrorCategory.InvalidArgument, null)); return; } // Only a single file path is allowed. if (paths.Count != 1) { string message = StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionPathInvalidNotSingle, _definitionName, _definitionPath); WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNamePathInvalidNotSingle", ErrorCategory.InvalidArgument, null)); return; } resolvedPath = paths[0]; } List <Job2> jobs = JobManager.GetJobToStart(_definitionName, resolvedPath, _definitionType, this, false); if (jobs.Count == 0) { string message = (_definitionType != null) ? StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound2, _definitionType, _definitionName) : StringUtil.Format(RemotingErrorIdStrings.StartJobDefinitionNotFound1, _definitionName); WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameNotFound", ErrorCategory.ObjectNotFound, null)); return; } if (jobs.Count > 1) { string message = StringUtil.Format(RemotingErrorIdStrings.StartJobManyDefNameMatches, _definitionName); WriteError(new ErrorRecord(new RuntimeException(message), "StartJobFromDefinitionNameMoreThanOneMatch", ErrorCategory.InvalidResult, null)); return; } // Start job. Job2 job = jobs[0]; job.StartJob(); // Write job object to host. WriteObject(job); return; } if (_firstProcessRecord) { _firstProcessRecord = false; PSRemotingJob job = new PSRemotingJob(ResolvedComputerNames, Operations, ScriptBlock.ToString(), ThrottleLimit, _name); job.PSJobTypeName = s_startJobType; this.JobRepository.Add(job); WriteObject(job); } // inject input if (InputObject != AutomationNull.Value) { foreach (IThrottleOperation operation in Operations) { ExecutionCmdletHelper helper = (ExecutionCmdletHelper)operation; helper.Pipeline.Input.Write(InputObject); } } } // ProcessRecord
public Handle StartJob(IJobOptions jobOptions) { var options = jobOptions as SpeJobOptions; return(JobManager.Start(options).Handle); }
// awake is called before any Start functions void Awake() { GenerateMap(); jobManager = JobManager.Instance; }
void OnApplicationQuit() { _instance = null; }
private void OnDestroy() { instance = null; }
public IQueryable <JobDetail> GetAll() { var jobManager = new JobManager(); return(jobManager.GetAllJobs().AsQueryable <JobDetail>());; }
/// <summary> /// 中断正在进行的发送接线过程,无论是异步与同步。 /// </summary> public override void Break() { JobManager.Break(); }
public IJob GetJob(Handle handle) { var job = JobManager.GetJob(handle); return(job == null ? null : new SpeJob(job)); }