Ejemplo n.º 1
0
        public void AddJobWithTheSameNameTest()
        {
            var scheduler = new Scheduler();

            scheduler.AddJob("Test", () => { }, Schedule.EveryDay().At(9, 00), DateTime.Today);

            Action a = () => scheduler.AddJob("Test", () => { }, Schedule.EveryDay().At(9, 00), DateTime.Today);

            a.Should().ThrowExactly <ArgumentException>();
        }
Ejemplo n.º 2
0
        public void ShouldInvokeJobBasedOnWaitSource()
        {
            // arrange
            var jobExecuted = new ManualResetEvent(false);

            var trigger = new ManualTrigger();

            scheduler.AddJob <SetOnExecute>(cfg => cfg.UseWaitSource(trigger).WithParameter(jobExecuted));

            // act
            trigger.TriggerNow();

            // assert
            Assert.That(jobExecuted.WaitOne(TimeSpan.FromSeconds(0.1)), Is.True, "Job should be executed");
        }
Ejemplo n.º 3
0
        public void PopJobTest()
        {
            Job       job1   = new Job("PopJob test 1", owner, 6, (float)5.0);
            Job       job2   = new Job("PopJob test 2", owner, 1, (float)1.2);
            Scheduler target = new Scheduler();

            target.AddJob(job1);
            System.Threading.Thread.Sleep(1);
            target.AddJob(job2);

            Job expected = job1;
            Job actual   = target.PopJob();

            Assert.AreEqual(expected.name, actual.name);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 创建一个读取报文任务
        /// </summary>
        /// <param name="identity">标识符</param>
        /// <param name="enableBit">占用位</param>
        /// <param name="filter">筛选器</param>
        /// <param name="context">要传递的上下文</param>
        public void Read(string identity, int enableBit, IReadFilter filter, object context = null)
        {
            Job4Agent job = new Job4Agent(identity, enableBit
                                          , new AgentTask(null, filter, Action_Read, context));

            Scheduler.AddJob(job);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 创建一个写入报文任务
        /// </summary>
        /// <param name="identity">标识符</param>
        /// <param name="enableBit">占用位</param>
        /// <param name="packet">筛选器</param>
        /// <param name="context">要传递的上下文</param>
        public void Send(string identity, int enableBit, byte[] packet, object context = null)
        {
            Job4Agent job = new Job4Agent(identity, enableBit
                                          , new AgentTask(packet, null, Action_Send, context));

            Scheduler.AddJob(job);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Запускаем/Перезапускаем Cron
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="period"></param>
        private void ConfigureSheduler(string fileName, int period)
        {
            // Если не дефолт - значит Job уже назначен - удаляем его
            if (_neededChangeJob)
            {
                _scheduler.RemoveJob(jobId);

                if (_playerFile != null)
                {
                    _playerFile.Dispose();
                    _playerFile = null;
                }
            }

            // Если период стал 'выключено' или имя файла пустое - на выход, тут делать больше нечего.
            if (period == 0 || fileName == string.Empty)
            {
                return;
            }

            // Создаем наш объект проигрывания.
            _playerFile = new PlayWavFile(_logger, fileName);

            // Создаем новое задание с новыми параметрами
            jobId = _scheduler.AddJob <PlayEveryTimeJob>(cfg => cfg.UseCron(CrontabPatterns.GetIntervalPattern(period)).WithParameter(_playerFile));

            // Установим признак что задача уже есть запущенная
            _neededChangeJob = true;
        }
Ejemplo n.º 7
0
        public async Task Start()
        {
            // construct a scheduler factory
            StdSchedulerFactory factory = new StdSchedulerFactory();

            // get a scheduler
            Scheduler = await factory.GetScheduler();

            await Scheduler.Start();

            IJobDetail job = JobBuilder.Create <RemoveOldEventsJob>()
                             .WithIdentity(RemoveOldEventsJobKey)
                             .UsingJobData(new JobDataMap()
            {
                { Constants.CommonDataKey.FQCS_SCHEDULER, this },
                { Constants.CommonDataKey.SETTINGS, RemoveOldEventsJobSettings },
                { Constants.CommonDataKey.SERVICE_PROVIDER, serviceProvider },
                { Constants.CommonDataKey.JOB_INFO, new JobInfo() }
            }).StoreDurably(true).Build();
            await Scheduler.AddJob(job, true);

            job = JobBuilder.Create <SendUnsentEventsJob>()
                  .WithIdentity(SendUnsentEventsJobKey)
                  .UsingJobData(new JobDataMap()
            {
                { Constants.CommonDataKey.FQCS_SCHEDULER, this },
                { Constants.CommonDataKey.SETTINGS, SendUnsentEventsJobSettings },
                { Constants.CommonDataKey.SERVICE_PROVIDER, serviceProvider },
                { Constants.CommonDataKey.JOB_INFO, new JobInfo() }
            }).StoreDurably(true).Build();
            await Scheduler.AddJob(job, true);
        }
Ejemplo n.º 8
0
        public void Test1()
        {
            Scheduler.InitializeScheduler();

            // This job is a one-shot job. This means that the job will execute once,
            // then get removed from the job pool.
            Scheduler.AddJob("One-time job", () => {
                Console.WriteLine("This is a one-shot job.");
            });

            // You can also use continuation calls. If set, the continuation method
            // will execute after the job has finished. Therefore, it is not available for
            // scheduled jobs, as they never finish.
            Scheduler.ContinueWith("One-time job", () => {
                Console.WriteLine("The one-shot job has finished executing.");
            });

            // This job is a repeating job, meaning it
            // runs every cycle of the supplied Cron expression.
            Scheduler.AddJob("GitHub-Updater", () => {
                Console.WriteLine("[" + DateTime.Now.ToString("F") + "] GitHub updated.");
            }, new CronExpression("* * * *"));

            // This job is a delayed job. Like the one-shot job, it only runs once,
            // but with a delay.
            Scheduler.AddJob("Schedule logger", () => {
                Console.WriteLine("Current amount of jobs in job pool: " + Scheduler.GetJobCount() + ".");
            }, JobDelay.FromMinutes(1));

            // Scheduler.HaltMainThread() is used to halt the main thread,
            // if there are no other halting statements.
            // This prevents the program from exiting, before all jobs are run.
            // The main thread will continue, when the job pool is empty.
            Scheduler.HaltMainThread();
        }
Ejemplo n.º 9
0
    private void Apply()
    {
        if (!Dirty)
        {
            return;
        }
        if (texture == null)
        {
            Debug.LogError("Cannot apply when the texture is null!");
            return;
        }

        if (TexJob == null)
        {
            TexJob = new ScheduledJob();
        }
        else
        {
            if (TexJob.State == JobState.PENDING)
            {
                Dirty = false;
                return;
            }
        }
        TexJob.State          = JobState.IDLE;
        TexJob.Action         = texture.Apply;
        TexJob.UponCompletion = UponTextureApplied;

        SetRendererTexture();
        Scheduler.AddJob(TexJob);
        Dirty = false;
    }
Ejemplo n.º 10
0
        public void TestAddJob()
        {
            scheduler.AddJob(job1);
            scheduler.AddJob(job2);
            scheduler.AddJob(job3);

            Assert.AreEqual(true, scheduler.HasJobs(), "Scheduler did not contain jobs");

            Job[] jobs = scheduler.GetJobs();
            Assert.AreEqual("3,20,Michael", jobs[0].ToString(), "Job2 did not match");
            Assert.AreEqual("4,40,Michael", jobs[1].ToString(), "Job1 did not match");
            Assert.AreEqual("1,60,Michael", jobs[2].ToString(), "Job3 did not match");
        }
Ejemplo n.º 11
0
        public void TestAddJob()
        {
            scheduler.AddJob(Job1);
            scheduler.AddJob(Job2);
            scheduler.AddJob(Job3);

            Assert.AreEqual(true, scheduler.HasJobs(), "Scheduler did not contain Jobs");

            Job[] Jobs = scheduler.GetJobs();
            Assert.AreEqual("job2", Jobs[0].ToString(), "Job2 did not match");
            Assert.AreEqual("job1", Jobs[1].ToString(), "Job1 did not match");
            Assert.AreEqual("job3", Jobs[2].ToString(), "Job3 did not match");
        }
Ejemplo n.º 12
0
        private void ConfigureSheduler()
        {
            // Если у нас уже изменеения
            if (_neededChangeJob)
            {
                #region Remove existing jobs

                if (_scheduler != null)
                {
                    // Удалим все задания
                    foreach (var guid in jobsDictionary)
                    {
                        _scheduler.RemoveJob(guid.Key);
                        _logger.Information($"Remove job for {guid.Value} with guid: {guid.Key}");
                    }

                    _scheduler.Dispose();
                    _scheduler = null;
                    // Раз задания удалили все - очищаем и хранилку их.
                    jobsDictionary.Clear();
                }

                if (_playerFile != null)
                {
                    _playerFile.Dispose();
                    _playerFile = null;
                }

                #endregion
            }

            // Если количество отметок больше нуля И файл проигрывания указан - добавляем задание.
            if (_tsLists.Count > 0 && !string.IsNullOrEmpty(FileNameToPlay))
            {
                if (_scheduler == null)
                {
                    _scheduler = new Scheduler();
                }

                // Создаем наш объект проигрывания.
                if (_playerFile == null)
                {
                    _playerFile = new PlayWavFile(_logger, FileNameToPlay);
                }

                // Удаляем дубликаты если есть.
                var jobsTimeLists = _tsLists.Distinct().ToList();

                foreach (var timeAt in jobsTimeLists)
                {
                    var newGuid = _scheduler.AddJob <PlayFileAtTimeJob>(cfg => cfg
                                                                        .UseCron(CrontabPatterns.GetConcretePatterns(timeAt)).WithParameter(_playerFile));

                    jobsDictionary.Add(newGuid, timeAt);
                    _logger.Information($"Create Job for {timeAt} by GUID: {newGuid}, with play file: {FileNameToPlay}");
                }
                _neededChangeJob = true;
            }
        }
Ejemplo n.º 13
0
        public SessionCache(TimeSpan sessionTimeoutInterval) : base(CacheReapPolicy.None, ExpirationPolicy.SinceLastAccessedTime, expirationDuration: sessionTimeoutInterval)
        {
            _cleaner = new Scheduler <IJob>(SchedulerPolicy.DisposeWhenFinished | SchedulerPolicy.RemoveJobOnError | SchedulerPolicy.DontThrow);
            var job = JobBuilder.For(Cleanup).RunAsyncronously().RunOnce(DateTime.Now.Add(sessionTimeoutInterval)).Repeat.OnInterval(sessionTimeoutInterval).Build();

            _cleaner.AddJob(job);
            _cleaner.Start();
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Save([FromForm] JobViewModel model, bool trigger)
        {
            var jobModel   = model.Job;
            var jobDataMap = (await Request.GetJobDataMapForm()).GetModel(Services);

            var result = new ValidationResult();

            model.Validate(result.Errors);
            ModelValidator.Validate(jobDataMap, result.Errors);

            if (result.Success)
            {
                var jobData = jobDataMap.GetQuartzJobDataMap();

                if (model?.Job?.CustomFormDataJsonModel?.Length > 0)
                {
                    if (jobData == null)
                    {
                        jobData = new JobDataMap();
                    }
                    if (jobData.ContainsKey("CustomData"))
                    {
                        jobData.Remove("CustomData");
                    }
                    jobData.Add("CustomData", model.Job.CustomFormDataJsonModel);
                }

                IJobDetail BuildJob(JobBuilder builder)
                {
                    return(builder
                           .OfType(Type.GetType(jobModel.Type, true))
                           .WithIdentity(jobModel.JobName, jobModel.Group)
                           .WithDescription(jobModel.Description)
                           .SetJobData(jobData)
                           .RequestRecovery(jobModel.Recovery)
                           .Build());
                }

                if (jobModel.IsNew)
                {
                    await Scheduler.AddJob(BuildJob(JobBuilder.Create().StoreDurably()), replace : false);
                }
                else
                {
                    var oldJob = await GetJobDetail(JobKey.Create(jobModel.OldJobName, jobModel.OldGroup));

                    await Scheduler.UpdateJob(oldJob.Key, BuildJob(oldJob.GetJobBuilder()));
                }

                if (trigger)
                {
                    await Scheduler.TriggerJob(JobKey.Create(jobModel.JobName, jobModel.Group));
                }
            }

            return(Json(result));
        }
Ejemplo n.º 15
0
        public void RemoveJobTest()
        {
            Scheduler target = new Scheduler();
            Job       job    = new Job("RemoveJob test", owner, 4, (float)1.4);

            target.AddJob(job);
            target.RemoveJob(job);
            Assert.IsNull(target.PopJob());
        }
Ejemplo n.º 16
0
 public void AddJobTest()
 {
     Owner owner = new Owner("Testuser"+userId++);
       Scheduler target = new Scheduler();
       Job job = new Job("AddJob Test", owner, 6, 4);
       target.AddJob(job);
      Job job2 = target.PopJob();
       Assert.AreSame(job, job2);
 }
Ejemplo n.º 17
0
        public void AddJobTest()
        {
            Owner     owner  = new Owner("Testuser" + userId++);
            Scheduler target = new Scheduler();
            Job       job    = new Job("AddJob Test", owner, 6, 4);

            target.AddJob(job);
            Job job2 = target.PopJob();

            Assert.AreSame(job, job2);
        }
Ejemplo n.º 18
0
        public void AddJobsTest()
        {
            var scheduler = new Scheduler();

            scheduler.Start();

            scheduler.AddJob("Test", () => { }, Schedule.EveryDay().At(9, 00), DateTime.Today);
            scheduler.AddJob("Test2", () => { }, Schedule.EveryMonth().OnFirstDay().At(9, 00), DateTime.Today);

            DateTime next1;

            if (DateTime.Now.Hour >= 9)
            {
                next1 = DateTime.Today.AddDays(1).AddHours(9);
            }
            else
            {
                next1 = DateTime.Today.AddHours(9);
            }

            DateTime next2;

            if (DateTime.Today.Day == 1)
            {
                next2 = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1, 9, 0, 0);
            }
            else if (DateTime.Today.Month == 12)
            {
                next2 = new DateTime(DateTime.Today.Year + 1, 1, 1, 9, 0, 0);
            }
            else
            {
                next2 = new DateTime(DateTime.Today.Year, DateTime.Today.Month + 1, 1, 9, 0, 0);
            }

            scheduler.Jobs.Should().BeEquivalentTo(new object[]
            {
                new { Name = "Test", Description = "Run every day, at 9:00", Status = JobStatus.Active, NextRunTime = next1 },
                new { Name = "Test2", Description = "Run on the first day of every month, at 9:00", Status = JobStatus.Active, NextRunTime = next2 },
            });
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            var scheduler = new Scheduler();

            Console.WriteLine("Adding WriteDot job");

            var writeDotId = scheduler.AddJob <WriteDot>(cfg => cfg.RunEvery(TimeSpan.FromSeconds(1)));

            Console.WriteLine("Adding WriteComma job");

            var writeCommaId = scheduler.AddJob <WriteComma>(cfg => cfg.RunWithSequence(DateTimeOffset.Now, x => x.AddMinutes(5)));

            scheduler.AddJob <CronJob>(cfg => cfg.UseCron("*/4 * * * *"));

            Console.WriteLine("Adding parameterized jobs");
            var paramJob1 = scheduler.AddJob <ParameterizedJob>(cfg => cfg
                                                                .RunEvery(TimeSpan.FromSeconds(1))
                                                                .WithParameter("First parameter value"));

            var paramJob2 = scheduler.AddJob <ParameterizedJob>(cfg => cfg
                                                                .RunEvery(TimeSpan.FromSeconds(3))
                                                                .WithParameter("Second parameter value"));

            Console.ReadLine();

            Console.WriteLine("Removing WriteDot job");

            scheduler.RemoveJob(writeDotId);

            Console.WriteLine("Removing WriteComma job");

            scheduler.RemoveJob(writeCommaId);

            Console.WriteLine("Removing second parametrized job");
            scheduler.RemoveJob(paramJob2);

            Console.WriteLine("Removing first parametrized job");
            scheduler.RemoveJob(paramJob1);

            Console.ReadLine();
        }
Ejemplo n.º 20
0
        public void UpdateSchedule(ScheduleModel scheduleModel)
        {
            var jobName = scheduleModel.JobName;

            IJobDetail job = CreateJob(scheduleModel.JobName, scheduleModel.Name);

            var triggerName = UnitHelper.GenerateNewGuid();

            ITrigger trigger = CreateTrigger(triggerName, scheduleModel);

            Scheduler.AddJob(job, true);
        }
Ejemplo n.º 21
0
        private void ScheduleDeletion(List <Tuple <ulong, ulong> > tweetIds)
        {
            var job = new SchedulerJob
            {
                JobType     = SchedulerJobType.DeleteStatus,
                IdsToDelete = tweetIds.Select(t => t.Item1).ToList(),
                AccountIds  = tweetIds.Select(t => t.Item2).ToList(),
                TargetTime  = DeletionDate + DeletionTime.TimeOfDay,
                Text        = Text
            };

            Scheduler.AddJob(job);
        }
Ejemplo n.º 22
0
        public void JobCanBeAdded()
        {
            var fileName = "SchedulerTests.JobCanBeAdded.json";

            try
            {
                // Arrange
                var contextList = new Mock <ITwitterContextList>();
                var config      = new Mock <ITwitterConfiguration>();

                var scheduler = new Scheduler(fileName, contextList.Object, config.Object);

                var job = new SchedulerJob
                {
                    JobType    = SchedulerJobType.Test,
                    AccountIds = new List <ulong> {
                        123
                    },
                    FilesToAttach = new List <string> {
                        "1", "2", "3"
                    },
                    IdsToDelete = new List <ulong> {
                        456
                    },
                    InReplyToStatus = 678,
                    TargetTime      = new DateTime(1, 2, 3, 4, 5, 6),
                    Text            = "hello world"
                };

                // Act
                scheduler.AddJob(job);

                // Assert
                string json    = File.ReadAllText(fileName);
                var    jobList = JsonConvert.DeserializeObject <List <SchedulerJob> >(json);

                Assert.IsNotNull(jobList);
                Assert.AreEqual(1, jobList.Count);
                CollectionAssert.AreEquivalent(job.AccountIds, jobList[0].AccountIds);
                Assert.AreEqual(job.InReplyToStatus, jobList[0].InReplyToStatus);
                Assert.AreEqual(job.TargetTime, jobList[0].TargetTime);
                Assert.AreEqual(job.Text, jobList[0].Text);
                Assert.AreEqual(job.JobType, jobList[0].JobType);
                CollectionAssert.AreEquivalent(job.IdsToDelete, jobList[0].IdsToDelete);
                CollectionAssert.AreEquivalent(job.FilesToAttach, jobList[0].FilesToAttach);
            }
            finally
            {
                File.Delete(fileName);
            }
        }
        public void ScheduleTweet(string text, ulong?inReplyTo, IEnumerable <ulong> accountIds, IEnumerable <string> mediaFileNames)
        {
            var job = new SchedulerJob
            {
                JobType         = SchedulerJobType.CreateStatus,
                Text            = text,
                AccountIds      = accountIds.ToList(),
                TargetTime      = ScheduleDate + ScheduleTime.TimeOfDay,
                InReplyToStatus = inReplyTo ?? 0,
                FilesToAttach   = mediaFileNames.ToList()
            };

            Scheduler.AddJob(job);
        }
Ejemplo n.º 24
0
        private void ScheduleTweet()
        {
            var job = new SchedulerJob
            {
                JobType         = SchedulerJobType.CreateStatus,
                Text            = Text,
                AccountIds      = Accounts.Where(a => a.Use).Select(a => a.Context.UserId).ToList(),
                TargetTime      = ScheduleDate + ScheduleTime.TimeOfDay,
                InReplyToStatus = InReplyTo?.Id ?? 0,
                FilesToAttach   = AttachedMedias.Select(m => m.FileName).ToList()
            };

            Scheduler.AddJob(job);
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            var schedule = Schedule.EveryDay().EveryMinute().From(0, 00).Until(23, 59);

            var scheduler = new Scheduler();

            scheduler.AddJob("Test", ScheduledJob, schedule, DateTime.Today);

            scheduler.Start();

            Console.ReadKey();

            scheduler.Stop();
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<EnglishHello>().As<IHello>();

            builder.RegisterType<SampleJob>().AsSelf();

            var container = builder.Build();

            var scheduler = new Scheduler(containerFactory: new AutofacContainerFactory(container));

            scheduler.AddJob<SampleJob>(cfg => cfg.RunEvery(TimeSpan.FromSeconds(1)));

            Console.ReadLine();
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            var scheduler = new Scheduler();

            Console.WriteLine("Adding WriteDot job");

            var jobId = scheduler.AddJob<WriteDot>(new JobSetup() {WaitSource = new IntervalWaitSource(TimeSpan.FromSeconds(1))});

            Console.ReadLine();

            Console.WriteLine("Removing WriteDot job");

            scheduler.RemoveJob(jobId);

            Console.ReadLine();
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <EnglishHello>().As <IHello>();

            builder.RegisterType <SampleJob>().AsSelf();

            var container = builder.Build();

            var scheduler = new Scheduler(containerFactory: new AutofacContainerFactory(container));

            scheduler.AddJob <SampleJob>(cfg => cfg.RunEvery(TimeSpan.FromSeconds(1)));

            Console.ReadLine();
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            IScheduler scheduler   = new Scheduler();
            string     clustername = null;
            string     username    = null;

            if (args.Length != 2)
            {
                Console.Error.WriteLine("Usage: Finish clustername username ");
                return;
            }
            clustername = args[0];
            username    = args[1];

            scheduler.Connect(clustername);

            ISchedulerJob job = scheduler.CreateJob();

            job.UnitType             = JobUnitType.Core;
            job.MinimumNumberOfCores = 1;
            job.MaximumNumberOfCores = 1;


            scheduler.AddJob(job);

            ISchedulerTask task = job.CreateTask();

            task.CommandLine = @"ping -t localhost";

            job.AddTask(task);


            scheduler.SubmitJob(job, username, null);
            Console.WriteLine("job {0} Submitted ", job.Id);

            Thread.Sleep(12 * 1000);

            job.Refresh();
            Console.WriteLine("Job {0} State {1}", job.Id, job.State);

            ((ISchedulerJobV3)job).Finish();
            Thread.Sleep(10000);
            job.Refresh();
            task.Refresh();
            Console.WriteLine("After finish Job {0} State {1} message {2}", job.Id, job.State, task.Output);
        }
Ejemplo n.º 30
0
        public void JobIsExecutedInThread()
        {
            // Arrange
            var contextList = new Mock <ITwitterContextList>();
            var config      = new Mock <ITwitterConfiguration>();

            var waitHandle = new ManualResetEventSlim(false);

            var proc = new Mock <IJobProcessor>();

            proc.Setup(p => p.Process(It.IsAny <SchedulerJob>())).Returns(Task.CompletedTask).Callback(
                () => waitHandle.Set()).Verifiable();

            var scheduler = new Scheduler("SchedulerTests.JobIsExecutedInThread.json", contextList.Object, config.Object,
                                          proc.Object, 20);

            scheduler.Start();
            bool set;

            try
            {
                var job = new SchedulerJob
                {
                    JobType    = SchedulerJobType.Test,
                    TargetTime = DateTime.Now.AddMilliseconds(-1),
                    AccountIds = new List <ulong> {
                        1
                    },
                    Text = "test"
                };
                scheduler.AddJob(job);

                // Act
                set = waitHandle.Wait(2000);
            }
            finally
            {
                scheduler.Stop();
            }

            // Assert
            Assert.IsTrue(set);
            proc.Verify(p => p.Process(It.IsAny <SchedulerJob>()), Times.Once());
        }
Ejemplo n.º 31
0
        public void ContainsTest()
        {
            Scheduler target = new Scheduler();

              // Add jobs and assert
              uint max = 10;
              Job[] jobs = new Job[max];
              for (uint i = 1; i <= max; i++) {
            Job job = new Job("Contains test "+i, owner, 1, i/2);
            jobs[i - 1] = job;
            target.AddJob(job);
            Assert.IsTrue(target.Contains(job));
              }
              // Remove jobs and assert
              for (uint i = max - 1; i > 0; i--) {
            target.RemoveJob(jobs[i]);
            Assert.IsFalse(target.Contains(jobs[i]));
              }
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            var scheduler = new Scheduler();

            Console.WriteLine("Adding WriteDot job");

            var jobId = scheduler.AddJob <WriteDot>(new JobSetup()
            {
                WaitSource = new IntervalWaitSource(TimeSpan.FromSeconds(1))
            });

            Console.ReadLine();

            Console.WriteLine("Removing WriteDot job");

            scheduler.RemoveJob(jobId);

            Console.ReadLine();
        }
Ejemplo n.º 33
0
        public void ContainsTest()
        {
            Scheduler target = new Scheduler();

            // Add jobs and assert
            uint max = 10;

            Job[] jobs = new Job[max];
            for (uint i = 1; i <= max; i++)
            {
                Job job = new Job("Contains test " + i, owner, 1, i / 2);
                jobs[i - 1] = job;
                target.AddJob(job);
                Assert.IsTrue(target.Contains(job));
            }
            // Remove jobs and assert
            for (uint i = max - 1; i > 0; i--)
            {
                target.RemoveJob(jobs[i]);
                Assert.IsFalse(target.Contains(jobs[i]));
            }
        }
Ejemplo n.º 34
0
        private async Task <IActionResult> AddEditJobDetails(JobDetails model, bool replace)
        {
            try
            {
                var jobDetail = new JobDetailImpl(model.Name,
                                                  model.Group,
                                                  Type.GetType(model.JobType),
                                                  model.Durable,
                                                  model.RequestsRecovery)
                {
                    Description = model.Description
                };
                jobDetail.Validate();
                await Scheduler.AddJob(jobDetail, replace).ConfigureAwait(false);

                return(NoContent());
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "AddEditJobDetails");
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message));
            }
        }
Ejemplo n.º 35
0
        public int LaunchFile(string filename, bool debug) {
            var clusterEnv = new ClusterEnvironment(_project.GetProperty(ClusterOptions.RunEnvironmentSetting));

            if (debug) {
                EnsureHiddenForm();
                EnsureListenerThread();
            }

            string workingDir, publishUrl;
            if (clusterEnv.HeadNode == "localhost") {
                workingDir = _project.GetProperty(ClusterOptions.WorkingDirSetting);
                if (String.IsNullOrWhiteSpace(workingDir)) {
                    workingDir = Path.Combine(Path.GetTempPath(), "HpcPyDebug" + Guid.NewGuid().ToString());
                }
                if (!Directory.Exists(workingDir)) {
                    Directory.CreateDirectory(workingDir);
                }

                publishUrl = "file://" + workingDir;
            } else {
                workingDir = GetWorkingDir(clusterEnv);

                // make sure we have a valid deployement dir as well
                string deploymentDir;
                if (!TryGetDeploymentDir(out deploymentDir)) {
                    return VSConstants.S_OK;
                }
                publishUrl = deploymentDir;
            }            

            string exe, arguments;
            if (!TryBuildCommandLine(debug, clusterEnv, filename, workingDir, out exe, out arguments) || 
                !TryPublishProject(clusterEnv, publishUrl)) {
                return VSConstants.S_OK;
            }

            if (clusterEnv.HeadNode == "localhost") {
                // run locally               
                if (debug) {
                    var startInfo = new ProcessStartInfo(exe, arguments);

                    LaunchRedirectedToVsOutputWindow(startInfo, false);
                } else {
                    Process.Start(exe, arguments);
                }
            } else {
                EnsureGeneralPane();

                var commandLine = exe + " " + arguments;

                var scheduler = new Scheduler();
                scheduler.Connect(clusterEnv.HeadNode);
                var job = CreateSchedulerJob(commandLine, clusterEnv, scheduler, debug);

                scheduler.AddJob(job);
                SetStatus("Scheduling job on server...");

                ScheduleJob(scheduler, job);
            }

            return VSConstants.S_OK;
        }
Ejemplo n.º 36
0
        public void TotalNumberOfJobsTest()
        {
            Scheduler target = new Scheduler();

              // Add jobs and assert
              uint max = 10;
              Job[] jobs = new Job[max];
              Assert.AreEqual((uint)0, target.TotalNumberOfJobs());
              for (uint i = 1; i <= max; i++) {
            Job job = new Job("TotalNumberOfJobs test"+i, owner, 1, i/2);
            jobs[i - 1] = job;
            target.AddJob(job);
            Assert.AreEqual(i, target.TotalNumberOfJobs());
              }

              // Remove jobs and assert
              for (uint i = max - 1; i > 0; i--) {
            target.RemoveJob(jobs[i]);
            Assert.AreEqual(i, target.TotalNumberOfJobs());
              }
        }
Ejemplo n.º 37
0
 public void RemoveJobTest()
 {
     Scheduler target = new Scheduler();
       Job job = new Job("RemoveJob test", owner, 4, (float)1.4);
       target.AddJob(job);
       target.RemoveJob(job);
       Assert.IsNull(target.PopJob());
 }
Ejemplo n.º 38
0
        public void PopJobTest()
        {
            Job job1 = new Job("PopJob test 1", owner, 6, (float)5.0);
              Job job2 = new Job("PopJob test 2", owner, 1, (float)1.2);
              Scheduler target = new Scheduler();
              target.AddJob(job1);
              System.Threading.Thread.Sleep(1);
              target.AddJob(job2);

              Job expected = job1;
              Job actual = target.PopJob();
              Assert.AreEqual(expected.name, actual.name);
        }