예제 #1
0
        public void TestEveryYear()
        {
            var cron = CronHelper.EveryYear(1);

            Assert.Equal("0 0 0 1 1 ?", cron.ToString());
            Assert.Equal("每年的1月1日0时0分0秒", cron.GetDescription());
        }
예제 #2
0
        public void TestEveryMonth()
        {
            var cron = CronHelper.EveryMonth(new byte[] { 10, 20 }, 8, 20);

            Assert.Equal("0 20 8 10,20 * ?", cron.ToString());
            Assert.Equal("每月的10、20日的8时20分0秒", cron.GetDescription());
        }
예제 #3
0
        public void TestEveryDay()
        {
            var cron = CronHelper.EveryDay(15, 30);

            Assert.Equal("0 30 15 * * ?", cron.ToString());
            Assert.Equal("每日的15时30分0秒", cron.GetDescription());
        }
예제 #4
0
        public void TestFromTime()
        {
            var time = DateTime.Now;
            var cron = CronHelper.FromTime(time);

            Assert.Equal($"{time.Second} {time.Minute} {time.Hour} {time.Day} {time.Month} ? {time.Year}", cron.ToString());
        }
예제 #5
0
        public void IsANewScanDue_ShouldReturnTrue()
        {
            var pattern        = "0 0 * * *";
            var last_scan_date = DateTime.Now.AddDays(-2);

            Assert.IsTrue(CronHelper.IsANewScanDue(pattern, last_scan_date));
        }
예제 #6
0
        public void IsANewScanDue_ShouldReturnFalse()
        {
            var pattern        = "0 0 * * *";
            var last_scan_date = DateTime.Now;

            Assert.IsFalse(CronHelper.IsANewScanDue(pattern, last_scan_date));
        }
예제 #7
0
        public bool IsScanDueFromSchedule(ApplicationProfile app)
        {
            app.id = $"{_veracodeRepository.GetAllApps().SingleOrDefault(x => x.app_name == app.application_name).app_id}";
            var lastScan = _veracodeRepository.GetLatestScan(app.id);

            if (lastScan == null)
            {
                _logger.LogWarning($"[{app.application_name}] Has not had a scan yet, the first scan is due.");
                return(true);
            }

            if (lastScan.build.analysis_unit[0].status != BuildStatusType.ResultsReady)
            {
                _logger.LogWarning($"[{app.application_name}] Currently has a scan in progress in the status of [{lastScan.build.analysis_unit[0].status}]");
            }


            if (CronHelper.IsANewScanDue(app.policy_schedule, lastScan.build.analysis_unit[0].published_date))
            {
                var dueDays = CronHelper.HowManyDaysAgo(app.policy_schedule, lastScan.build.analysis_unit[0].published_date);
                _logger.LogWarning($"[{app.application_name}] last scan was {lastScan.build.analysis_unit[0].published_date.ToLongDateString()} and was due {dueDays} days ago.");
                return(true);
            }
            else
            {
                _logger.LogInformation($"A scan is not due according to the schedule.");
                _logger.LogInformation($"Last scan completed at {lastScan.build.analysis_unit[0].published_date.ToLongDateString()}");
            }

            _logger.LogInformation($"A new scan does not need to be started.");
            return(false);
        }
예제 #8
0
        /// <summary>
        /// 文件改动事件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        private void OnChanged(object source, FileSystemEventArgs e)
        {
            var jobList = (List <JobDetail>)XmlHelper.XmlDeserialize(typeof(List <JobDetail>), Config.ConfigPath);

            if (jobList != null)
            {
                foreach (var item in jobList)
                {
                    if (dicTimer.Any(o => o.Key == item.Name))
                    {
                        var timer = dicTimer[item.Name];
                        if (item.JobType != timer.JobDetail.JobType || item.CronExpression != timer.JobDetail.CronExpression)
                        {
                            timer.JobDetail = CronHelper.SetCron(item);
                            if (timer.JobDetail.WorkType == WorkType.Loop)
                            {
                                timer.Interval = timer.JobDetail.Interval;
                            }
                            else
                            {
                                timer.Interval = 1000;
                            }
                        }
                        timer.JobDetail.Enabled   = item.Enabled;
                        timer.JobDetail.StartTime = item.StartTime;
                        timer.JobDetail.EndTime   = item.EndTime;
                    }
                    else
                    {
                        SetTimer(item);
                    }
                }
            }
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var cron = WeihanLi.Common.Helpers.Cron.CronExpression.Parse(CronExpression);

            var next = cron.GetNextOccurrence();

            while (!stoppingToken.IsCancellationRequested && next.HasValue)
            {
                var now = DateTimeOffset.UtcNow;

                if (now >= next)
                {
                    if (ConcurrentAllowed)
                    {
                        _    = ProcessAsync(stoppingToken);
                        next = CronHelper.GetNextOccurrence(CronExpression);
                        if (next.HasValue)
                        {
                            Logger.LogInformation("Next at {next}", next);
                        }
                    }
                    else
                    {
                        var firewall = RedisManager.GetFirewallClient($"Job_{GetType().FullName}_{next:yyyyMMddHHmmss}", TimeSpan.FromMinutes(3));
                        if (await firewall.HitAsync())
                        {
                            // 执行 job
                            await ProcessAsync(stoppingToken);

                            next = CronHelper.GetNextOccurrence(CronExpression);
                            if (next.HasValue)
                            {
                                Logger.LogInformation("Next at {next}", next);
                                var delay = next.Value - DateTimeOffset.UtcNow;
                                if (delay > TimeSpan.Zero)
                                {
                                    await Task.Delay(delay, stoppingToken);
                                }
                            }
                        }
                        else
                        {
                            Logger.LogInformation("正在执行 job,不能重复执行");
                            next = CronHelper.GetNextOccurrence(CronExpression);
                            if (next.HasValue)
                            {
                                await Task.Delay(next.Value - DateTimeOffset.UtcNow, stoppingToken);
                            }
                        }
                    }
                }
                else
                {
                    // needed for graceful shutdown for some reason.
                    // 1000ms so it doesn't affect calculating the next
                    // cron occurence (lowest possible: every second)
                    await Task.Delay(next.Value - DateTimeOffset.UtcNow, stoppingToken);
                }
            }
        }
예제 #10
0
        public void TestEveryHour()
        {
            var cron = CronHelper.EveryHour(5, 10);

            Assert.Equal("10 5 * * * ?", cron.ToString());
            Assert.Equal("每时5分10秒", cron.GetDescription());
        }
예제 #11
0
        private View GetView(int actionId)
        {
            var ruleAndAction = CronHelper.GetRuleAndAction(actionId);

            View view = (View)ruleAndAction["view"];

            return(view);
        }
예제 #12
0
        public void TestSerial1()
        {
            var cron           = CronHelper.EveryDay(15, 30);
            var cronJsonString = Newtonsoft.Json.JsonConvert.SerializeObject(cron);
            var cron2          = Newtonsoft.Json.JsonConvert.DeserializeObject <CronHelper>(cronJsonString);

            Assert.Equal(cron.ToString(), cron2.ToString());
        }
예제 #13
0
        public void HowManyDaysAgo_ShouldReturn10()
        {
            var pattern        = "0 0 * * *";
            var last_scan_date = DateTime.Now.AddDays(-10);
            var days           = CronHelper.HowManyDaysAgo(pattern, last_scan_date);

            Assert.IsTrue(9.0 < days && days < 10.0);
        }
예제 #14
0
 private void DeleteAwsCron(Cron cron)
 {
     try
     {
         CronHelper.deleteCron(cron);
     }
     catch (Exception)
     {
     }
 }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);


            CronHelper.AddTask <CronUtil>("0 0 0/1 * * ? ");
        }
        public void Test_CronHelper_FindNextUpdateTime_Returns()
        {
            // Arrange
            var baseDateTime         = new DateTime(2020, 2, 18, 15, 50, 30);
            var expectedDateTime     = new DateTime(2020, 2, 18, 16, 00, 00);
            var cronEveryWeekdayAt16 = "0 16 * * 1-5";
            // Run
            var result = CronHelper.FindNextUpdateTime(baseDateTime, cronEveryWeekdayAt16);

            // Assert
            Assert.Equal(result, expectedDateTime);
        }
        public async Task <Exchange> ExchangeRatesBySourceAndTarget(string source, string target)
        {
            source = source?.ToUpper();
            target = target?.ToUpper();
            // Check source and target currency codes are valid
            var currencies = Currencies();

            if (!(currencies.Any(x => x.Code.Equals(source)) && currencies.Any(x => x.Code.Equals(target))))
            {
                _logger.LogError("Source or Target currency invalid!");
                throw new ArgumentException("Source or Target currency invalid");
            }

            var requestUrl = "?base=" + source + "&symbols=" + target;

            if (_cache.TryGetValue(requestUrl, out Exchange responseRate))
            {
                return(responseRate);
            }
            string cron       = "0 16 * * 1-5"; // Every weekday at 16.00 pm
            var    expiryDate = CronHelper.FindNextUpdateTime(DateTime.Now, cron);
            var    request    = new HttpRequestMessage(HttpMethod.Get, BASE_CURRENCY_EXCHANGE_SERVICE_URL + requestUrl);

            using (var client = _clientFactory.CreateClient())
            {
                var response = await client.SendAsync(request);

                if (response.IsSuccessStatusCode)
                {
                    var responseStream = await response.Content.ReadAsStringAsync();

                    var jo           = JObject.Parse(responseStream);
                    var currencyRate = jo["rates"][target].ToString();
                    var updateDate   = jo["date"].ToString();
                    var exchange     = new Exchange
                    {
                        SourceCurrency = source,
                        TargetCurrency = target,
                        ExchangeRate   = (decimal)double.Parse(currencyRate),
                        Date           = DateTime.Parse(updateDate)
                    };
                    _logger.LogInformation("Exchange information read successful!", exchange);
                    _cache.Set(requestUrl, exchange, expiryDate);
                    return(exchange);
                }
                else
                {
                    _logger.LogError("Exchange rates cannot be read!", response.StatusCode);
                }
            }
            return(default);
예제 #18
0
        public static void MainTest()
        {
            // http://www.quartz-scheduler.org/documentation/quartz-2.3.0/tutorials/crontrigger.html
            var nextTickUtc   = CronHelper.GetNextOccurrence("0 15 10 * * ?");
            var nextTickLocal = CronHelper.GetNextOccurrence("0 15 10 * * ?", TimeZoneInfo.Local);

            Console.WriteLine($"@utc next tick: {nextTickUtc.GetValueOrDefault().DateTime.ToStandardTimeString()}  {Environment.NewLine} local next tick:{nextTickLocal.GetValueOrDefault().DateTime.ToStandardTimeString()}");

            var nextTicks = CronHelper.GetNextOccurrences("0 15 10-20 * * ?", TimeSpan.FromHours(6), TimeZoneInfo.Local).Take(5).ToArray();

            foreach (var tick in nextTicks)
            {
                Console.WriteLine(tick.DateTime.ToStandardTimeString());
            }
        }
예제 #19
0
        public DemoJob()
        {
            JobInfo                 = new hangfire_jobs();
            JobInfo.id              = "5dad40031b46632a24823333";
            JobInfo.job_name        = "写日志";
            JobInfo.cron_expression = CronHelper.MinuteInterval(1);
            JobInfo.job_note        = "每一分钟写一次测试日志";
            JobInfo.send_email      = 1;
            JobInfo.email           = "*****@*****.**";
            JobInfo.excute_status   = 1;
            JobInfo.job_status      = 1;
            JobInfo.create_time     = DateTime.Now;
            JobInfo.last_time       = JobInfo.create_time;

            TaskId         = JobInfo.id;
            CronExpression = JobInfo.cron_expression;
        }
예제 #20
0
        /// <summary>
        /// Timer
        /// </summary>
        /// <param name="jobDetail"></param>
        private void SetTimer(JobDetail jobDetail)
        {
            TWTimer timer = new TWTimer();

            timer.JobDetail = CronHelper.SetCron(jobDetail);
            if (timer.JobDetail.WorkType == WorkType.Loop)
            {
                timer.Interval = timer.JobDetail.Interval;
            }
            else
            {
                timer.Interval = 1000;
            }
            timer.AutoReset = true;
            timer.Enabled   = true;
            timer.Elapsed  += new ElapsedEventHandler(OnTimedEvent);
            dicTimer.Add(timer.JobDetail.Name, timer);
        }
예제 #21
0
        private bool IsActive(int id)
        {
            bool?active = null;

            try
            {
                var    crons = CronHelper.getCron();
                string key   = id.ToString();
                if (crons.ContainsKey(key))
                {
                    active = ((Dictionary <string, object>)crons[key])[STATE].ToString() == ENABLED;
                }
            }
            catch { }

            if (!active.HasValue)
            {
                return(true);
            }

            return(active.Value);
        }
예제 #22
0
        public virtual IHttpActionResult Delete(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, Messages.IdIsMissing)));
                }

                View view = GetView(null);
                if (view == null)
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, string.Format(Messages.ViewNameNotFound, AppViewName))));
                }
                if (!view.IsDeletable())
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, Messages.ViewIsUnauthorized)));
                }

                int?appId = Maps.Instance.AppExists(id, Convert.ToInt32(Maps.Instance.DuradosMap.Database.GetUserID()));
                if (!appId.HasValue)
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.NotFound, string.Format(Messages.ItemWithIdNotFound, id, AppViewName))));
                }

                string guid = GetMasterGuid();

                string qstring = "id=" + guid;


                try
                {
                    Durados.Web.Mvc.Infrastructure.ProductMaintenance productMaintenece = new Durados.Web.Mvc.Infrastructure.ProductMaintenance();
                    productMaintenece.RemoveApp(id);
                }
                catch (Exception exception)
                {
                    Maps.Instance.DuradosMap.Logger.Log("myApps", "delete", id, exception, 1, "The app " + id + " has productMaintenece errors");
                }

                //url = GetDeleteAppUrl(id);
                //string response = Durados.Web.Mvc.Infrastructure.Http.GetWebRequest(url,string.Empty,string.Empty, 100000);
                //Dictionary<string, object> ret = Durados.Web.Mvc.UI.Json.JsonSerializer.Deserialize(response);

                try
                {
                    CronHelper.DeleteAllCrons(Maps.Instance.AppExists(id).Value.ToString());
                }
                catch (Exception exception)
                {
                    Maps.Instance.DuradosMap.Logger.Log("myApps", "delete", id, exception, 1, "Failed to delete all app crons");
                }


                try
                {
                    Webhook webhook = new Webhook();
                    try
                    {
                        webhook.Send(WebhookType.AppDeleted, GetBody(id, Maps.Instance.DuradosMap.Database.GetCurrentUsername()));
                        Maps.Instance.DuradosMap.Logger.Log("webhook", "AppDeleted", this.Request.Method.Method, null, 3, null, DateTime.Now);
                    }
                    catch (Exception exception)
                    {
                        webhook.HandleException(WebhookType.AppDeleted, exception);
                    }
                }
                catch { }

                string sql = "delete durados_App where name = '" + id + "'";
                (new SqlAccess()).ExecuteNonQuery(Maps.Instance.DuradosMap.connectionString, sql);


                Maps.Instance.DuradosMap.Logger.Log("myApps", "delete", "", null, 1, "The app " + id + " was deleted");
                //Maps.Instance.Restart(id);

                RestHelper.Refresh(id);

                FarmCachingSingeltone.Instance.ClearMachinesCache(id);


                //RefreshOldAdmin(id);

                return(Ok());
            }
            catch (Exception exception)
            {
                throw new BackAndApiUnexpectedResponseException(exception, this);
            }
        }
예제 #23
0
 private CronRequestInfo GetRequestInfo(Cron cron, bool test)
 {
     return(CronHelper.GetRequestInfo(cron, test));
 }
예제 #24
0
 private object GetTestRequest(CronRequestInfo requestInfo)
 {
     return(CronHelper.GetTestRequest(requestInfo));
 }
예제 #25
0
        protected override System.Web.Http.Results.OkNegotiatedContentResult <T> Ok <T>(T content)
        {
            if (!(content is IDictionary <string, object>))
            {
                return(base.Ok <T>(content));
            }

            IDictionary <string, object> response = (dynamic)content;
            Dictionary <string, Dictionary <string, object> > crons = null;


            if (response.Count == 2 && response.ContainsKey(DATA))
            {
                crons = CronHelper.getCron();
                foreach (Dictionary <string, object> item in (IEnumerable)response[DATA])
                {
                    bool   active = false;
                    string id     = null;
                    if (item.ContainsKey(ID))
                    {
                        id = item[ID].ToString();
                    }
                    else if (item.ContainsKey("id"))
                    {
                        id = item["id"].ToString();
                    }
                    if (id != null)
                    {
                        if (crons.ContainsKey(id))
                        {
                            active = ((Dictionary <string, object>)crons[id])[STATE].ToString() == ENABLED;
                        }
                        if (item.ContainsKey(ACTIVE))
                        {
                            item[ACTIVE] = active;
                        }
                        else
                        {
                            item.Add(ACTIVE, active);
                        }
                    }
                }
            }
            else if (response.ContainsKey(ID))
            {
                crons = CronHelper.getCron(new Cron()
                {
                    ID = System.Convert.ToInt32(response[ID])
                });
                bool active = false;
                if (crons.ContainsKey(response[ID].ToString()))
                {
                    active = ((Dictionary <string, object>)crons[response[ID].ToString()])[STATE].ToString() == ENABLED;
                }
                if (response.ContainsKey(ACTIVE))
                {
                    response[ACTIVE] = active;
                }
                else
                {
                    response.Add(ACTIVE, active);
                }
            }

            return(base.Ok <T>(content));
        }
예제 #26
0
 private void CreateOrUpdateAwsCron(Cron cron)
 {
     CronHelper.putCron(cron);
 }