Пример #1
0
        private static void ScheduleAfterInstall(string assemblyPath)
        {
            const string taskName    = "FileWall after install launch";
            const string taskComment = "Launches FileWall after install.";

            //Get a ScheduledTasks object for the local computer.
            var scheduledTasks = new ScheduledTasks();

            scheduledTasks.DeleteTask(taskName);

            // Create a task
            var task = scheduledTasks.CreateTask(taskName);

            // Fill in the program info
            task.ApplicationName = assemblyPath;
            task.Comment         = taskComment;

            task.Flags |= TaskFlags.RunOnlyIfLoggedOn | TaskFlags.DeleteWhenDone;

            // Set the account under which the task should run.
            task.SetAccountInformation(Environment.ExpandEnvironmentVariables("%USERNAME%"), (string)null);

            // Create a trigger to start the task every Sunday at 6:30 AM.
            task.Triggers.Add(new RunOnceTrigger(DateTime.Now));

            // Save the changes that have been made.
            task.Save();

            task.Run();

            // Close the task to release its COM resources.
            task.Close();
            // Dispose the ScheduledTasks to release its COM resources.
            scheduledTasks.Dispose();
        }
Пример #2
0
 public static bool GetShotDownSetting(ref ShutDownConfig config)
 {
     try
     {
         //创建任务计划类
         ScheduledTasks st        = new ScheduledTasks();
         string[]       taskNames = st.GetTaskNames();
         config.IsUsed = false;
         foreach (string name in taskNames)
         {
             if (name == "AutoShutDown.job")
             {
                 config.IsUsed = true;
                 break;
             }
         }
         string fileDircetoryPath = AppDomain.CurrentDomain.BaseDirectory; StringBuilder shutdownbat = new StringBuilder();
         string path = fileDircetoryPath + "gjjh.bat";
         if (File.Exists(path))
         {
             StreamReader sr  = new StreamReader(path);
             string       str = sr.ReadLine();
             sr.Close();
             config.ShutDownHour    = str.Substring(3, str.IndexOf(':') - 3);
             config.ShutDownMin     = str.Substring(str.IndexOf(':') + 1, 2).Trim();
             config.ShutDownWaitSec = str.Substring(str.LastIndexOf(' ') + 1);
         }
         return(true);
     }
     catch (Exception ex)
     {
         SeatManageComm.WriteLog.Write("获取关机计划失败!" + ex.Message);
         return(false);
     }
 }
Пример #3
0
        /// <summary>Schedule FileWall to start on logon.</summary>
        private static void ScheduleStartup(string assemblyPath)
        {
            //Get a ScheduledTasks object for the local computer.
            var scheduledTasks = new ScheduledTasks();

            scheduledTasks.DeleteTask("FileWall Launch");

            // Create a task
            var task = scheduledTasks.CreateTask("FileWall Launch");

            // Fill in the program info
            task.ApplicationName = assemblyPath;
            task.Comment         = "Launches FileWall when user logs on.";

            task.Flags |= TaskFlags.RunOnlyIfLoggedOn;

            // Set the account under which the task should run.
            task.SetAccountInformation(Environment.ExpandEnvironmentVariables("%USERNAME%"), (string)null);

            // Create a trigger to start the task every Sunday at 6:30 AM.
            task.Triggers.Add(new OnLogonTrigger());

            // Save the changes that have been made.
            task.Save();
            // Close the task to release its COM resources.
            task.Close();
            // Dispose the ScheduledTasks to release its COM resources.
            scheduledTasks.Dispose();
        }
Пример #4
0
        public async Task MainLoopAsync(int timeslicems)
        {
            logger.Trace("Entered loop");
            var lastPing = DateTime.UtcNow;

            await SendPingAsync();

            while (_looping)
            {
                try
                {
                    await WaitEventAsync(timeslicems);
                } catch (OperationCanceledException)
                {
                    logger.Trace("Timeout");
                }
                finally
                {
                    var now = DateTime.UtcNow;
                    if ((now - lastPing).TotalSeconds >= 30)
                    {
                        await SendPingAsync();

                        lastPing = now;
                    }
                    if (ScheduledTasks != null)
                    {
                        logger.Trace("Running idle tasks");
                        ScheduledTasks.Invoke(this);
                        ScheduledTasks = null;
                    }
                    IdleTasks?.Invoke(this);
                }
            }
        }
Пример #5
0
        public async Task <int> InsertSheduledTasktAsync(ScheduledTasks task)
        {
            string query = "INSERT INTO `ScheduledTasks`" +
                           "(`Type`,`Comments`,`Duration`,`CreatedUser`,`Effectivedate`,`CreatedDateTime`,`IsDelete`,`RepeatType`,`StartDateTime`,`EndDateTime`,`IsDelete`,`IsActive`) " +
                           "VALUES (@Type,@Comments,@Duration,@CreatedUser,@Effectivedate,@CreatedDateTime,@IsDelete,@RepeatType,@StartDateTime,@EndDateTime,@IsDelete,@IsActive);";

            IEnumerable <KeyValuePair <string, object> > parameters = new List <KeyValuePair <string, object> >()
            {
                new KeyValuePair <string, object>("@Type", task.Type),
                new KeyValuePair <string, object>("@Comments", task.Comments),
                new KeyValuePair <string, object>("@Duration", task.Duration),
                new KeyValuePair <string, object>("@CreatedUser", task.CreatedUser),
                new KeyValuePair <string, object>("@Effectivedate", TimeConverterMethods.ConvertDateTimeToTimeStamp(task.Effectivedate)),
                new KeyValuePair <string, object>("@CreatedDateTime", TimeConverterMethods.ConvertDateTimeToTimeStamp(task.CreatedDateTime)),
                new KeyValuePair <string, object>("@IsDelete", 0),
                new KeyValuePair <string, object>("@RepeatType", task.RepeatType),
                new KeyValuePair <string, object>("@StartDateTime", TimeConverterMethods.ConvertDateTimeToTimeStamp(task.StartDateTime)),
                new KeyValuePair <string, object>("@EndDateTime", TimeConverterMethods.ConvertDateTimeToTimeStamp(task.EndDateTime)),
                new KeyValuePair <string, object>("@IsActive", task.IsActive)
            };

            int id = await SqliteConnector.ExecuteInsertQueryAsync(query, parameters, true);

            query = "UPDATE `ScheduledTasks` SET `ReferenceNumber`=@ReferenceNumber WHERE `Id`=@Id";

            parameters = new List <KeyValuePair <string, object> >()
            {
                new KeyValuePair <string, object>("@ReferenceNumber", id.ToString("STASK000000")),
                new KeyValuePair <string, object>("@Id", id)
            };

            await SqliteConnector.ExecuteNonQueryAsync(query, parameters, true);

            return(id);
        }
Пример #6
0
        private void Prox_Ejec()
        {
            string         nombreApp = (Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)).Replace("Config.exe", "");
            ScheduledTasks Tareas    = new ScheduledTasks();

            TaskScheduler.Task tarea = Tareas.OpenTask(nombreApp);
            if (chkInicioW.Checked && tarea != null)
            {
                string proxima = tarea.NextRunTime.ToString();
                label18.Visible  = true;
                label18.Text     = ("Proxima ejecucion: " + proxima);
                chkEdit.Visible  = true;
                TimePicker.Value = Convert.ToDateTime(proxima);
                tarea.Close();

                Dehab();
            }
            else
            {
                label18.Visible    = false;
                label18.Text       = "";
                chkEdit.Visible    = false;
                chkInicioW.Checked = false;
            }
            chkEdit.Checked = false;
            Tareas.Dispose();
        }
Пример #7
0
        public ActionResult <Response <Game> > BeginGame([FromHeader] int playerID)
        {
            try
            {
                //Create the player object and begin the game.
                Player          hostPlayer = new Player(playerID);
                Response <Game> response   = new GameDAL().BeginGame(hostPlayer);

                //If the response is successful schedule code to run to update the GameState after the time periods have passed
                if (response.IsSuccessful())
                {
                    HubInterface hubInterface = new HubInterface(_hubContext);
                    ScheduledTasks.ScheduleGameInPlayingState(response.Data, hubInterface);
                    ScheduledTasks.ScheduleCompleteGame(response.Data, hubInterface);

                    //Update all clients that the game is now in a starting state and the game will be playing soon
                    hubInterface.UpdateGameInStartingState(response.Data);
                }
                return(response);
            }
            //Catch any error associated with invalid model data
            catch (InvalidModelException e)
            {
                return(new Response <Game>(e.Msg, e.Code));
            }
            //Catch any unhandled / unexpected server errrors
            catch
            {
                return(StatusCode(500));
            }
        }
Пример #8
0
        /// <summary>
        /// Cancels if running
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void CancelIfRunning <T>()
            where T : IScheduledTask
        {
            var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));

            ((ScheduledTaskWorker)task).CancelIfRunning();
        }
Пример #9
0
        /// <summary>
        /// Executes the queued tasks.
        /// </summary>
        private void ExecuteQueuedTasks()
        {
            Logger.LogInformation("ExecuteQueuedTasks");

            // Execute queued tasks
            lock (_taskQueue)
            {
                var list = new List <Tuple <Type, TaskOptions> >();

                while (_taskQueue.TryDequeue(out var item))
                {
                    if (list.All(i => i.Item1 != item.Item1))
                    {
                        list.Add(item);
                    }
                }

                foreach (var enqueuedType in list)
                {
                    var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == enqueuedType.Item1);

                    if (scheduledTask.State == TaskState.Idle)
                    {
                        Execute(scheduledTask, enqueuedType.Item2);
                    }
                }
            }
        }
Пример #10
0
        public async Task <ScheduledTasks> InsertSheduledTasktAsync(ScheduledTasks task)
        {
            await _insertTaskSemaphoreSlim.WaitAsync();

            try
            {
                UserEntity userEntity = await _userModel.GetUserDetailsAsync();

                task.CreatedUser = userEntity.Id;
                int tId = await _taskModel.InsertSheduledTasktAsync(task);

                task = await _taskModel.GetScheduledTasksByIdAsync(tId);

                IList <ScheduledTasks> tasks = ScheduledTasks.ToList();
                tasks.Add(task);

                ScheduledTasks = tasks;
                CurrentUser    = userEntity;

                return(task);
            }
            catch (Exception k)
            {
                applicationErrorLog.ErrorLog("Task", "Insert scheduled task", k.ToString());
                return(task);
            }
            finally
            {
                _insertTaskSemaphoreSlim.Release();
            }
        }
Пример #11
0
        private void RunStartupTasks()
        {
            var path = Path.Combine(ApplicationPaths.CachePath, "startuptasks.txt");

            // ToDo: Fix this shit
            if (!File.Exists(path))
            {
                return;
            }

            List <string> lines;

            try
            {
                lines = _fileSystem.ReadAllLines(path).Where(i => !string.IsNullOrWhiteSpace(i)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();

                foreach (var key in lines)
                {
                    var task = ScheduledTasks.FirstOrDefault(i => string.Equals(i.ScheduledTask.Key, key, StringComparison.OrdinalIgnoreCase));

                    if (task != null)
                    {
                        QueueScheduledTask(task, new TaskOptions());
                    }
                }

                _fileSystem.DeleteFile(path);
            }
            catch
            {
                return;
            }
        }
Пример #12
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void QueueScheduledTask <T>()
            where T : IScheduledTask
        {
            var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));

            QueueScheduledTask(scheduledTask);
        }
Пример #13
0
 /// <summary>
 /// Runs all tasks until no more scheduled tasks are left.
 /// If a pending task schedules an additional task it will also be executed.
 /// </summary>
 public void RunTasksUntilIdle()
 {
     while (ScheduledTasks.Any())
     {
         RunPendingTasks();
     }
 }
Пример #14
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="options">Task options</param>
        public void QueueScheduledTask <T>(TaskExecutionOptions options)
            where T : IScheduledTask
        {
            var scheduledTask = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));

            QueueScheduledTask(scheduledTask, options);
        }
Пример #15
0
 public static bool CreateShutDown(ShutDownConfig config)
 {
     try
     {
         //创建任务计划类
         ScheduledTasks st        = new ScheduledTasks();
         string[]       taskNames = st.GetTaskNames();
         //删除原有计划
         foreach (string name in taskNames)
         {
             if (name == "AutoShutDown.job")
             {
                 st.DeleteTask("AutoShutDown.job");
                 break;
             }
         }
         //读取路径
         string        fileDircetoryPath = AppDomain.CurrentDomain.BaseDirectory;
         StringBuilder shutdownbat       = new StringBuilder();
         string        path = fileDircetoryPath + "gjjh.bat";
         //判断是否启用
         if (config.IsUsed)
         {
             //创建关机批处理
             shutdownbat.AppendFormat("at {0}:{1} shutdown -s -t {2}", config.ShutDownHour, config.ShutDownMin, config.ShutDownWaitSec);
             if (!File.Exists(path))
             {
                 FileStream fs = File.Create(path);
                 fs.Close();
             }
             StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("GB2312"));
             sw.Write(shutdownbat);
             sw.Flush();
             sw.Close();
             //创建任务计划
             Task         task    = st.CreateTask("AutoShutDown");
             DateTime     addTIme = DateTime.Parse(string.Format("{0}:{1}", config.ShutDownHour, config.ShutDownMin)).AddMinutes(-10);
             DailyTrigger dt      = new DailyTrigger(short.Parse(addTIme.Hour.ToString()), short.Parse(addTIme.Minute.ToString()));
             task.Triggers.Add(dt);
             task.SetAccountInformation(Environment.UserName, (string)null);
             task.Flags           = TaskFlags.RunOnlyIfLoggedOn | TaskFlags.SystemRequired;
             task.ApplicationName = fileDircetoryPath + "gjjh.bat";
             task.Comment         = "触摸屏终端自动关机";
             task.Save();
             task.Close();
         }
         else if (File.Exists(path))
         {
             //删除批处理
             File.Delete(path);
         }
         return(true);
     }
     catch (Exception ex)
     {
         SeatManageComm.WriteLog.Write("添加关机计划失败!" + ex.Message);
         return(false);
     }
 }
Пример #16
0
 public ManageTaskUserControl(Action <ContentItemEnum> changeContent, OneTimeTasks transactionEntity, ScheduledTasks schtrans) : this(changeContent)
 {
     _onetimetaskEntity = transactionEntity;
     if (schtrans != null)
     {
         _schtaskEntity = schtrans;
     }
 }
Пример #17
0
        /// <summary>
        /// Adds the tasks.
        /// </summary>
        /// <param name="tasks">The tasks.</param>
        public void AddTasks(IEnumerable <IScheduledTask> tasks)
        {
            var myTasks = ScheduledTasks.ToList();

            myTasks.AddRange(tasks.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger)));

            ScheduledTasks = myTasks.ToArray();
        }
Пример #18
0
        /// <summary>
        /// Cancels if running and queue.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="options">Task options.</param>
        public void CancelIfRunningAndQueue <T>(TaskOptions options)
            where T : IScheduledTask
        {
            var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));

            ((ScheduledTaskWorker)task).CancelIfRunning();

            QueueScheduledTask <T>(options);
        }
 public ScheduleTaskBinder(ScheduledTasks taskEntity)
 {
     ReferenceNumber = taskEntity.ReferenceNumber;
     Duration        = taskEntity.Duration.ToString();
     Effectivedate   = taskEntity.Effectivedate;
     Task_Type       = "Scheduled";
     Comments        = taskEntity.Comments;
     Type            = taskEntity.Type == 1 ? ContentTaskTypesEnum.Appointment.ToString() : ContentTaskTypesEnum.Task.ToString();
 }
Пример #20
0
 private void dataGridViewScheduled_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
 {
     if (e.RowIndex >= 0)
     {
         ScheduleTaskBinder ScheduleTaskBinder = _ScheduleTaskBinder[e.RowIndex];
         ScheduledTasks     schtasks           = _applicationService.ScheduledTasks.First(t => t.ReferenceNumber == ScheduleTaskBinder.ReferenceNumber);
         _changeContentMainFormAction(ContentItemEnum.ManageTask, schtasks);
     }
 }
Пример #21
0
 /// <summary>
 ///     Add a Task to the queue
 /// </summary>
 /// <param name="task">Task to add</param>
 /// <returns></returns>
 public Task <T> Enqueue <T>(Task <T> task, string taskName = "")
 {
     if (!string.IsNullOrEmpty(taskName))
     {
         task.Tag(taskName);
     }
     ScheduledTasks.Enqueue(task);
     TaskManagerWorkerLoop();
     return(task);
 }
Пример #22
0
        protected void Application_Start(object sender, EventArgs e)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Configurations\log4net.config");

            log4net.Config.XmlConfigurator.Configure(new FileInfo(path));

            WebBase.HttpApplication = this;
            this._scheduledTasks    = new ScheduledTasks();
            this._scheduledTasks.Start();
        }
Пример #23
0
 public ScheduleTaskBinder(ScheduledTasks taskEntity)
 {
     ReferenceNumber = taskEntity.ReferenceNumber;
     Comments        = taskEntity.Comments;
     Duration        = taskEntity.Duration.ToString();
     Effectivedate   = taskEntity.Effectivedate;
     RepeatType      = taskEntity.RepeatType;
     Type            = taskEntity.Type == 1 ? ContentTaskTypesEnum.Appointment.ToString() : ContentTaskTypesEnum.Task.ToString();
     Status          = taskEntity.IsActive ? "Active" : "Disabled";
 }
Пример #24
0
        public void QueueIfNotRunning <T>()
            where T : IScheduledTask
        {
            var task = ScheduledTasks.First(t => t.ScheduledTask.GetType() == typeof(T));

            if (task.State != TaskState.Running)
            {
                QueueScheduledTask <T>(new TaskOptions());
            }
        }
Пример #25
0
        /// <summary>Delete on logon schedule.</summary>
        private static void DeleteSchedule()
        {
            //Get a ScheduledTasks object for the local computer.
            var scheduledTasks = new ScheduledTasks();

            try
            {
                scheduledTasks.DeleteTask("FileWall Launch");
            }
            catch { }
        }
Пример #26
0
        public MainWindow()
        {
            InitializeComponent();

            //local
            //scheduledTask = new ScheduledTasks("d8728cab-45da-4bad-849d-13c904450f5c","p8HxFcp1VeojgOx9p5RLBv6weZFLb/rO4DNKaJMHUqs=");

            //dev test environment
            //Do not change this else the system will not identify you.
            scheduledTask = new ScheduledTasks("7c433c07-b9b9-4e20-8f70-9092328aacd2",
                                               "1b9j/3WkdFqF8KOehoW4jJRLGWdjqSTpXqasoAGB8II=");
        }
Пример #27
0
        /// <summary>
        /// Adds the tasks.
        /// </summary>
        /// <param name="tasks">The tasks.</param>
        public void AddTasks(IEnumerable <IScheduledTask> tasks)
        {
            var myTasks = ScheduledTasks.ToList();

            var list = tasks.ToList();

            myTasks.AddRange(list.Select(t => new ScheduledTaskWorker(t, ApplicationPaths, this, JsonSerializer, Logger, _fileSystem)));

            ScheduledTasks = myTasks.ToArray();

            RunStartupTasks();
        }
Пример #28
0
        public async Task <ScheduledTasks> UpdateSheduledTaskListAsync(ScheduledTasks task)
        {
            await _taskModel.UpdateSheduledTaskListAsync(task);

            UserEntity userEntity = await _userModel.GetUserDetailsAsync();

            IEnumerable <ScheduledTasks> tasks = await _taskModel.GetScheduledTasksAsync();

            ScheduledTasks = tasks;
            CurrentUser    = userEntity;

            return(task);
        }
Пример #29
0
        /// <summary>
        /// Queues the scheduled task.
        /// </summary>
        /// <param name="task">The task.</param>
        /// <param name="options">The task options.</param>
        public void QueueScheduledTask(IScheduledTask task, TaskOptions options)
        {
            var scheduledTask = ScheduledTasks.FirstOrDefault(t => t.ScheduledTask.GetType() == task.GetType());

            if (scheduledTask == null)
            {
                Logger.LogError("Unable to find scheduled task of type {0} in QueueScheduledTask.", task.GetType().Name);
            }
            else
            {
                QueueScheduledTask(scheduledTask, options);
            }
        }
Пример #30
0
        private void bREG_Click(object sender, EventArgs e)
        {
            ScheduledTasks st = new ScheduledTasks();

            st.DeleteTask(TN);
            Task task = st.CreateTask(TN);

            task.ApplicationName = Path.Combine(Application.StartupPath, "U4ieServer.exe");
            task.Parameters      = " \"" + textBox1.Text + "\" \"" + comboBox1.Text + "\" \"" + textBox2.Text + "\" ";
            task.Triggers.Add(new DailyTrigger(10, 0));
            task.Save();
            task.DisplayForEdit();
        }