Ejemplo n.º 1
0
        private static void ReadAndExecuteTask(object sender, EventArgs e)
        {
            DateTime nextEvent = DateTime.Now.AddMilliseconds(Convert.ToInt64(AppConfig.TimerInterval));
            var      tasks     = _context.NotificationTasks.AsNoTracking().Where(t => t.NotificationTime >= DateTime.Now && t.NotificationTime <= nextEvent && t.Status == NotificationTaskStatusEnum.INITIAL).ToList();

            foreach (var t in tasks)
            {
                int taskId = t.TaskId;
                Task.Run(() =>
                {
                    var executer = new TaskExecuter(taskId);
                    _            = executer.ExecuteAsync();
                });
            }
        }
Ejemplo n.º 2
0
        public static void Main(string[] args)
        {
            _services = new ServiceCollection();

            /*_services.AddLogging(builder => builder
             *  .AddConsole()
             *  .AddFilter(level => level >= LogLevel.Information)
             * );*/
            //var loggerFactory = _services.BuildServiceProvider().GetService<ILoggerFactory>();
            var config = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory).AddJsonFile("appsettings.json").Build();

            AppConfig.ToolsConnectionString = config.GetConnectionString("ToolsConnection");
            AppConfig.ToolsOption           = new DbContextOptionsBuilder <ToolsContext>();
            AppConfig.ToolsOption /*.UseLoggerFactory(loggerFactory)*/.UseMySql(AppConfig.ToolsConnectionString, new MariaDbServerVersion(new Version(10, 4))
                                                                                );
            _services.AddDbContext <ToolsContext>(
                options => options /*.UseLoggerFactory(loggerFactory)*/.UseMySql(AppConfig.ToolsConnectionString, new MariaDbServerVersion(new Version(10, 4))
                                                                                 ));

            AppConfig.TwitterConnectionString = config.GetConnectionString("TwitterConnection");
            AppConfig.TwitterOption           = new DbContextOptionsBuilder <TwitterContext>();
            AppConfig.TwitterOption /*.UseLoggerFactory(loggerFactory)*/.UseMySql(AppConfig.ToolsConnectionString, new MariaDbServerVersion(new Version(10, 4))
                                                                                  );
            _services.AddDbContext <TwitterContext>(
                options => options /*.UseLoggerFactory(loggerFactory)*/.UseMySql(AppConfig.TwitterConnectionString, new MariaDbServerVersion(new Version(10, 4))
                                                                                 ));

            _provider  = _services.BuildServiceProvider();
            _context   = _provider.GetService <ToolsContext>();
            _twContext = _provider.GetService <TwitterContext>();

            _twitterSettings = config.GetSection("TwitterSettings");
            _tokens          = Tokens.Create(_twitterSettings["APIKey"], _twitterSettings["APISecret"], _twitterSettings["AccessKey"], _twitterSettings["AccessSecret"]);

            AppConfig.NFToken = config.GetSection("NF")?["Token"];

            //実行中になっているタスクを再スタート
            DateTime nextEvent = DateTime.Now.AddMilliseconds(Convert.ToInt64(AppConfig.TimerInterval));
            var      tasks     = _context.NotificationTasks.AsNoTracking().Where(t => t.NotificationTime >= DateTime.Now && t.NotificationTime <= nextEvent && (t.Status == NotificationTaskStatusEnum.INITIAL || t.Status == NotificationTaskStatusEnum.EXECUTING)).ToList();

            foreach (var t in tasks)
            {
                int taskId = t.TaskId;
                Task.Run(() =>
                {
                    var executer = new TaskExecuter(taskId);
                    _            = executer.ExecuteAsync();
                });
            }

            //タイマースタート
            _timer          = new System.Timers.Timer(AppConfig.TimerInterval);
            _timer.Elapsed += new ElapsedEventHandler(ReadAndExecuteTask);
            _timer.Start();

            //Twitterタスクタイマースタート
            _twitterTimer          = new System.Timers.Timer(AppConfig.TwitterTimerInterVal);
            _twitterTimer.Elapsed += new ElapsedEventHandler(RecordMyFollows);
            _twitterTimer.Start();

            BuildWebHost(args).Run();
        }
Ejemplo n.º 3
0
        private async Task HandleTextAsync(string replyToken, string userMessage, string userId)
        {
            var          message      = userMessage.Split(" ");
            DateTime     pushTime     = DateTime.Now;
            bool         doPush       = false;
            ISendMessage replyMessage = null;
            CommandEum   command;

            _ = message[0].TryParseStringValueToEnum <CommandEum>(out command);

            switch (command)
            {
            case CommandEum.JAfleetGa:
                replyMessage = new TextMessage(GALogics.GetReportStringMyNormal1(_context));
                break;

            case CommandEum.PlanNotice:
                string additional = string.Empty;
                if (message[1].StartsWith("a"))
                {
                    message[1] = DateTime.Now.AddMinutes(Int32.Parse(message[1].Replace("a", string.Empty))).ToString("yyyyMMddHHmm");
                }
                else if (message[1].Length == 4)
                {
                    additional = DateTime.Now.ToString("yyyyMMdd");
                }
                else if (message[1].Length == 8)
                {
                    additional = DateTime.Now.ToString("yyyy");
                }
                else if (message[1].Length == 10)
                {
                    additional = "20";
                }

                doPush = DateTime.TryParseExact(additional + message[1], "yyyyMMddHHmm", null, System.Globalization.DateTimeStyles.None, out pushTime);
                if (pushTime <= DateTime.Now)
                {
                    doPush = false;
                }
                string mes;
                if (doPush)
                {
                    mes = "予約しました";
                }
                else
                {
                    mes = "予約に失敗しました";
                }
                replyMessage = new TextMessage(mes);
                break;

            case CommandEum.PlanList:
                var  tasks     = _tContext.NotificationTasks.AsNoTracking().Where(t => t.NotificationTime >= DateTime.Now && t.NotificationTo == userId).OrderBy(t => t.NotificationTime).ToList();
                var  planList  = new StringBuilder();
                bool firstLine = true;
                foreach (var t in tasks)
                {
                    if (!firstLine)
                    {
                        planList.AppendLine();
                    }
                    else
                    {
                        firstLine = false;
                    }
                    planList.Append($"{t.NotificationTime?.ToString("yyyy/MM/dd HH:mm")}:{t.NotificationDetail} {t.Status.GetStringValue()}");
                }
                replyMessage = new TextMessage(planList.ToString());
                break;

            case CommandEum.ExceptionDelete:
                _context.Log.RemoveRange(_context.Log.Where(l => l.LogType == LogType.EXCEPTION));
                int result = _context.SaveChanges();
                replyMessage = new TextMessage($"{result}件削除しました");
                break;

            default:
                if (Regex.IsMatch(message[0], "[0-9]{4}") || Regex.IsMatch(message[0], "[0-9]{3}[a-zA-Z]{1}") || Regex.IsMatch(message[0], "[0-9]{2}[a-zA-Z]{2}"))
                {
                    replyMessage = new TextMessage($"googlechromes://ja-fleet.noobow.me/e/JA{message[0].ToUpper()}");
                }
                break;
            }

            await messagingClient.ReplyMessageAsync(replyToken, new List <ISendMessage> {
                replyMessage
            });

            if (doPush)
            {
                //task登録
                var nTask = new NotificationTask {
                    NotificationDetail = message[2], NotificationTime = pushTime, Status = NotificationTaskStatusEnum.INITIAL, NotificationTo = userId
                };
                _tContext.NotificationTasks.Add(nTask);
                _tContext.SaveChanges();

                if ((pushTime - DateTime.Now).TotalMilliseconds < AppConfig.TimerInterval)
                {
                    //1時間以内なら即座にタスクを実行
                    //1時間以上ならタイマーに任せる
                    _ = Task.Run(() =>
                    {
                        using (var serviceScope = _services.CreateScope())
                        {
                            var executer = new TaskExecuter(nTask.TaskId);
                            _            = executer.ExecuteAsync();
                        }
                    });
                }
            }
        }