コード例 #1
0
 public bool Create(CronTask model)
 {
     using (var db = NewDB())
     {
         db.CronTasks.Add(model);
         return(db.SaveChanges() > 0);
     }
 }
コード例 #2
0
        public ApiResult Add(CronTask model)
        {
            var service = Unity.GetService <ICronTaskService>();

            model.CreatedTime = DateTime.Now;
            model.Status      = TaskState.STOP;
            service.Create(model);
            return(new ApiResult());
        }
コード例 #3
0
        public bool Update(CronTask model)
        {
            using (var db = NewDB())
            {
                db.Entry(model).State = System.Data.Entity.EntityState.Modified;

                return(db.SaveChanges() > 0);
            }
        }
コード例 #4
0
 private object ToApiModel(CronTask task)
 {
     return(new
     {
         id = task.Id,
         name = task.Name,
         eventAlias = task.EventAlias,
         enabled = task.Enabled,
         month = task.Month,
         day = task.Day,
         hour = task.Hour,
         minute = task.Minute
     });
 }
コード例 #5
0
        /// <summary>
        /// ios android push msg
        /// </summary>
        /// <param name="pushtype">消息类型</param>
        /// <param name="tag">用户标签 umeng设置</param>
        /// <param name="starttime">发送时间</param>
        /// /// <param name="title">通知标题</param>
        /// <param name="content">通知内容</param>
        /// <param name="description">通知文字描述</param>
        /// <param name="thirdparty_id">开发者自定义消息标识ID</param>
        public static void PushMessage(string pushtype, string tag, string starttime, string title, string content, string description, string thirdparty_id, string tels = null)
        {
            //"{""where"":{""and"":[{""or"":[{""tag"":""1""}]}]}}";
            JObject json = null;

            if (!string.IsNullOrWhiteSpace(tag))
            {
                string jsonStr = @"{""where"":{""and"":[{""or"":[{""tag"":""" + tag + @"""}]}]}}";
                json = JObject.Parse(jsonStr);
            }
            PushIosMsg(pushtype, IsProduc, json, starttime, title, content, description, thirdparty_id);
            PushAndroidMsg(pushtype, IsProduc, json, starttime, title, content, description, thirdparty_id);
            if (!string.IsNullOrWhiteSpace(starttime))
            {
                CronTask.SetTask(tag, starttime, title, content, description, tels);
            }
        }
コード例 #6
0
        /// <summary>
        ///     Add a cron task to current scheduler with cron expression and the action.
        /// </summary>
        /// <param name="cronExpr">
        ///     A string that represents the cron expression.
        /// </param>
        /// <param name="action">
        ///     An action to run when the scheduled task is triggered.
        /// </param>
        /// <param name="taskId">
        ///     Task's id, which helps you to get a better control of the task. If it's null or empty, a random guid
        ///     will be generated.
        /// </param>
        /// <returns>
        ///     True if the task is scheduled successfully; otherwise, false.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     Throw if action is null.
        /// </exception>
        /// <exception cref="CronParserException">
        ///     Throw if failed to parse cronExpr.
        /// </exception>
        public bool AddTask(string cronExpr, Action action, string taskId = null)
        {
            if (action == null)
            {
                throw new ArgumentNullException(nameof(action));
            }

            var cron = CronInterpreter.Parse(cronExpr);
            var task = new CronTask
            {
                Id        = String.IsNullOrEmpty(taskId) ? Guid.NewGuid().ToString("N") : taskId,
                CronInfo  = cron,
                Action    = action,
                IsEnabled = true
            };

            return(AddTask(task));
        }
コード例 #7
0
        public ApiResult Update(CronTask model)
        {
            var service = Unity.GetService <ICronTaskService>();
            var theTask = service.Get(model.Id);

            if (theTask == null)
            {
                return(new ApiResult(ApiStatus.Fail, "任务不存在"));
            }

            theTask.ModifyTime           = DateTime.Now;
            theTask.TaskName             = model.TaskName;
            theTask.TaskParam            = model.TaskParam;
            theTask.CronExpressionString = model.CronExpressionString;
            theTask.ApiUri = model.ApiUri;
            theTask.Remark = model.Remark;
            service.Update(theTask);
            return(new ApiResult());
        }
コード例 #8
0
        public object SaveTask(HttpRequestParams request)
        {
            var id         = request.GetGuid("id");
            var name       = request.GetRequiredString("name");
            var eventAlias = request.GetString("eventAlias");
            var month      = request.GetInt32("month");
            var day        = request.GetInt32("day");
            var hour       = request.GetInt32("hour");
            var minute     = request.GetInt32("minute");
            var enabled    = request.GetRequiredBool("enabled");

            using (var session = Context.Require <DatabasePlugin>().OpenSession())
            {
                CronTask task;

                if (id.HasValue)
                {
                    task = session.Set <CronTask>().Single(s => s.Id == id.Value);
                }
                else
                {
                    task = new CronTask {
                        Id = Guid.NewGuid()
                    };
                    session.Set <CronTask>().Add(task);
                }

                task.Name       = name;
                task.EventAlias = eventAlias;
                task.Enabled    = enabled;
                task.Month      = month;
                task.Day        = day;
                task.Hour       = hour;
                task.Minute     = minute;
                session.SaveChanges();

                // reset cron event cache
                Context.Require <CronPlugin>().ReloadTasks();

                return(task.Id);
            }
        }
コード例 #9
0
ファイル: TmpPlugin.cs プロジェクト: qhtml5/system
        public object AddTimer(HttpRequestParams requestParams)
        {
            using (var db = Context.Require <DatabasePlugin>().OpenSession())
            {
                var time = DateTime.Now.AddMinutes(1);

                var t = new CronTask
                {
                    Id         = Guid.NewGuid(),
                    Enabled    = true,
                    EventAlias = $"event:{time.ToShortTimeString()}",
                    Name       = $"time:{time.ToShortTimeString()}"
                };

                db.Set <CronTask>().Add(t);
                db.SaveChanges();
            }

            Context.Require <CronPlugin>().ReloadTasks();

            return(200);
        }
コード例 #10
0
        public async Task <IActionResult> AddRssFeeds()
        {
            var cronTask = new CronTask(_repo);
            var result   = await cronTask.AddRssFeeds();

            return(Ok());



            // var blogs = await _repo.GetBlogs();
            // foreach (var blog in blogs)
            // {
            //     //TODO: Count blog feed for the blog
            //     //TODO: Delete feed if it's more than 20
            //     var blogFeed = await readRss(blog);
            //     if (blogFeed != null)
            //     {
            //         this._repo.Add(blogFeed);
            //     }
            // }
            // var cnt = await this._repo.SaveAll();

            // return Ok(cnt);
        }
コード例 #11
0
        /// <summary>
        ///     Add a cron task to current scheduler.
        /// </summary>
        /// <param name="task">
        ///     The cron task to schedule.
        /// </param>
        /// <returns>
        ///     True if the task is scheduled successfully; otherwise, false. If the <see cref="CronTask.IsEnabled"/>
        ///     of task is set to false, this operation will fail.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     Throw if the task is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     Throw if the Id, CronInfo or Action of the task is null.
        /// </exception>
        public bool AddTask(CronTask task)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            if (String.IsNullOrEmpty(task.Id) || task.CronInfo == null || task.Action == null)
            {
                throw new ArgumentException(nameof(task));
            }

            if (task.IsEnabled)
            {
                lock (_tasksLocker)
                {
                    this._scheduledTasks.Add(task);
                }

                return(true);
            }

            return(false);
        }
コード例 #12
0
        public void MultiTasks()
        {
            var cronExpr = "* * * * *";

            var counter_task = 0;
            var cronInfo     = CronInterpreter.Parse(cronExpr);
            var task         = new CronTask
            {
                Id        = Guid.NewGuid().ToString("N"),
                CronInfo  = cronInfo,
                IsEnabled = true,
                Action    = () =>
                {
                    ++counter_task;
                    Debug.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] Callback. ---Task 01");
                }
            };

            //  Adds tasks.
            var success_task = _scheduler.AddTask(task);

            var counter_expr = 0;
            var success_expr = _scheduler.AddTask(cronExpr, () =>
            {
                ++counter_expr;
                Thread.Sleep(TimeSpan.FromSeconds(3)); // Simulates time-consuming operation.
                Debug.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] Callback. ---Task 02");
            });

            var counter_info = 0;
            var success_info = _scheduler.AddTask(cronInfo, () =>
            {
                ++counter_info;
                Debug.WriteLine($"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] Callback. ---Task 03");
            });

            // Gets scheduled tasks.
            var scheduledTasks = _scheduler.ScheduledTasks();

            scheduledTasks.RemoveAt(0);
            var modifiedScheduledTasks = _scheduler.ScheduledTasks();

            // Removes task.
            var taskToRemove = scheduledTasks.Last();

            _scheduler.Remove(taskToRemove.Id);

            // Gets scheduled tasks again.
            modifiedScheduledTasks = _scheduler.ScheduledTasks();

            Thread.Sleep(TimeSpan.FromSeconds(135)); // Sets the test lifecycle.

            Assert.IsTrue(
                success_task &&
                success_expr &&
                success_info &&
                counter_task == 2 &&
                counter_expr == 2 &&
                counter_info == 0
                );
        }
コード例 #13
0
ファイル: Startup.cs プロジェクト: KazunoriHayashiNZ/Wacomi
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

            services.AddCors();
            services.AddMvc();
            // services.AddSingleton<IEmailSender, EmailSender>();

            // services.Configure<AuthMessageSenderOptions>(Configuration);
            // services.Configure<MvcOptions>(options =>
            // {
            //     options.Filters.Add(new RequireHttpsAttribute());
            // });
            services.Configure <CloudinarySettings>(Configuration.GetSection("CloudinarySettings"));
            services.Configure <AuthMessageSenderOptions>(Configuration.GetSection("MessageSenderOptions"));
            services.AddAutoMapper();
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("WacomiDbConnection")));
            //options.UseSqlServer(@"Server=db;Database=WacomiNZ;User=sa;Password=P@ssw0rd!!;"));
            services.AddScoped <IAuthRepository, AuthRepository>();
            services.AddScoped <IDataRepository, DataRepository>();

            services.AddIdentity <Account, IdentityRole>
                (o =>
            {
                // configure identity options
                o.Password.RequireDigit           = true;
                o.Password.RequireLowercase       = true;
                o.Password.RequireUppercase       = true;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
                o.Lockout.MaxFailedAccessAttempts = 20;
                o.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromHours(24);
                o.SignIn.RequireConfirmedEmail    = true;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // Configure JwtIssuerOptions
            //var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
            var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(opeionts =>
            {
                opeionts.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    //ValidateIssuer = false,
                    ValidIssuers     = new[] { Configuration.GetSection("JwtIssuerOptions:Issuer").Value },
                    ValidateAudience = false,
                    ClockSkew        = TimeSpan.Zero
                };
            });

            services.AddHangfire(config =>
                                 config.UseSqlServerStorage(Configuration.GetConnectionString("WacomiDbConnection")));

            var serviceProvider = services.BuildServiceProvider();

            serviceProvider.GetService <ApplicationDbContext>().Database.Migrate();
            this.cronTask = ActivatorUtilities.CreateInstance <CronTask>(serviceProvider);
            services.AddSingleton <IEmailSender, EmailSender>();
        }
コード例 #14
0
ファイル: CronCore.cs プロジェクト: Jerdak/CronM
        static TaskMatch MatchTasks(CronTask task)
        {
            //enum TaskMatch { Unset=0x00,Minute = 0x01, Hour = 0x02, DayOfMonth = 0x04, Month = 0x08, DayOfWeek = 0x16 ,Complete = 0x31};
            TaskMatch ret = TaskMatch.Unset;
            DateTime dt = DateTime.Now;// new DateTime(2011, 4, 26, 10, 17, 0);// DateTime.Today;

            //Console.WriteLine("Diff: " + ((TimeSpan)(dt - task.LastRun)).TotalSeconds.ToString());
            if ((dt - task.LastRun).TotalSeconds < 60) return ret;

            ParseMatch(task.Minute, dt.Minute,ref ret, TaskMatch.Minute);
            ParseMatch(task.Hour,	dt.Hour, ref ret, TaskMatch.Hour);
            ParseMatch(task.DayOfMonth, dt.Day, ref ret, TaskMatch.DayOfMonth);
            ParseMatch(task.Month, dt.Month, ref ret, TaskMatch.Month);
            ParseMatch(task.DayOfWeek, (int)dt.DayOfWeek, ref ret, TaskMatch.DayOfWeek);
            return ret;
        }
コード例 #15
0
 public static CronScheduleItem FromTask(CronTask task)
 {
     return(new CronScheduleItem(task.Id, task.EventAlias, task.GetPattern()));
 }