/// <summary> /// 处理单个定时任务,返回是否实际执行了 /// </summary> protected virtual bool HandleTaskInner(IScheduledTask executor) { var uow = UnitOfWork; using (uow.Scope()) { // 从数据库获取任务的最后执行时间,判断是否需要立刻执行 uow.Context.BeginTransaction(); var task = Get(executor.Key); var lastExecuted = task != null ? task.UpdateTime : DateTime.MinValue; if (!executor.ShouldExecuteNow(lastExecuted)) { return(false); } // 执行前使用事务更新数据库中的执行时间,防止多个进程托管同一个网站时重复执行 task = task ?? new ScheduledTask() { Id = executor.Key }; Save(ref task, t => t.UpdateTime = DateTime.UtcNow); uow.Context.FinishTransaction(); } // 执行定时任务 executor.Execute(); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. /// </summary> /// <param name="scheduledTask">The scheduled task.</param> /// <param name="applicationPaths">The application paths.</param> /// <param name="taskManager">The task manager.</param> /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> /// <exception cref="System.ArgumentNullException"> /// scheduledTask /// or /// applicationPaths /// or /// taskManager /// or /// jsonSerializer /// or /// logger /// </exception> public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem, ISystemEvents systemEvents) { if (scheduledTask == null) { throw new ArgumentNullException("scheduledTask"); } if (applicationPaths == null) { throw new ArgumentNullException("applicationPaths"); } if (taskManager == null) { throw new ArgumentNullException("taskManager"); } if (jsonSerializer == null) { throw new ArgumentNullException("jsonSerializer"); } if (logger == null) { throw new ArgumentNullException("logger"); } ScheduledTask = scheduledTask; ApplicationPaths = applicationPaths; TaskManager = taskManager; JsonSerializer = jsonSerializer; Logger = logger; _fileSystem = fileSystem; _systemEvents = systemEvents; InitTriggerEvents(); }
void Initialize(IChannelHandlerContext context) { // Avoid the case where destroy() is called before scheduling timeouts. // See: https://github.com/netty/netty/issues/143 switch (this.state) { case 1: case 2: return; } this.state = 1; IEventExecutor executor = context.Executor; this.lastReadTime = this.lastWriteTime = TimeUtil.GetSystemTime(); if (this.readerIdleTime.Ticks > 0) { this.readerIdleTimeout = executor.Schedule(ReadTimeoutAction, this, context, this.readerIdleTime); } if (this.writerIdleTime.Ticks > 0) { this.writerIdleTimeout = executor.Schedule(WriteTimeoutAction, this, context, this.writerIdleTime); } if (this.allIdleTime.Ticks > 0) { this.allIdleTimeout = executor.Schedule(AllTimeoutAction, this, context, this.allIdleTime); } }
/// <summary> /// 处理单个定时任务 /// </summary> /// <param name="executor">定时任务执行器</param> protected virtual void HandleTask(IScheduledTask executor) { // 执行任务并捕捉错误 bool executed = false; bool success = false; string error = null; try { executed = HandleTaskInner(executor); success = true; } catch (Exception e) { error = e.ToString(); } if (!executed && error == null) { return; } // 记录日志 using (UnitOfWork.Scope()) { var logRepository = ZKWeb.Application.Ioc.Resolve <IRepository <ScheduledTaskLog, Guid> >(); var log = new ScheduledTaskLog() { Task = Get(executor.Key), CreateTime = DateTime.UtcNow, Success = success, Error = error }; logRepository.Save(ref log); } }
private void AddOrUpdate(IScheduledTask scheduledTask) { string taskIdAsString = RedisConverter.ToString(scheduledTask.Id); if (this.serializer.CanDetermineEntityTypeFromContent) { this.provider.SetHashValues( RedisScheduledTaskRepository.ScheduledTasksHashKey, new Dictionary <string, byte[]>() { { taskIdAsString + "$Content", this.serializer.Serialize(scheduledTask) }, { taskIdAsString + "$RecurrenceDefinition", this.serializer.Serialize(scheduledTask.Schedule) } }); } else { using (IRedisTransaction transaction = this.provider.CreateTransaction()) { transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$Content", this.serializer.Serialize(scheduledTask)); transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$Type", RedisConverter.ToString(scheduledTask.GetType(), false)); transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$RecurrenceDefinition", this.serializer.Serialize(scheduledTask.Schedule)); transaction.SetHashValue(RedisScheduledTaskRepository.ScheduledTasksHashKey, taskIdAsString + "$RecurrenceDefinition$Type", RedisConverter.ToString(scheduledTask.Schedule.GetType(), false)); transaction.Commit(); } } }
/// <summary> /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. /// </summary> /// <param name="scheduledTask">The scheduled task.</param> /// <param name="applicationPaths">The application paths.</param> /// <param name="taskManager">The task manager.</param> /// <param name="logger">The logger.</param> /// <exception cref="ArgumentNullException"> /// scheduledTask /// or /// applicationPaths /// or /// taskManager /// or /// jsonSerializer /// or /// logger. /// </exception> public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, ILogger logger) { if (scheduledTask == null) { throw new ArgumentNullException(nameof(scheduledTask)); } if (applicationPaths == null) { throw new ArgumentNullException(nameof(applicationPaths)); } if (taskManager == null) { throw new ArgumentNullException(nameof(taskManager)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } ScheduledTask = scheduledTask; _applicationPaths = applicationPaths; _taskManager = taskManager; _logger = logger; InitTriggerEvents(); }
/// <summary> /// Sends the initial message to be sent to the proxy server. This method also starts a timeout task which marks /// the <seealso cref="#connectPromise"/> as failure if the connection attempt does not success within the timeout. /// </summary> private void sendInitialMessage(IChannelHandlerContext context) { long connectTimeoutMillis = this.connectTimeoutMillis; if (connectTimeoutMillis > 0) { connectTimeoutFuture = context.Executor.Schedule(() => { if (!connectPromise.IsCompleted) { ctx_c = context; ConnectFailure = new Exception(exceptionMessage("timeout")); } }, new TimeSpan(0, 0, 0, ConnectTimeoutMillis)); } object initialMessage = newInitialMessage(context); if (initialMessage != null) { sendToProxyServer(initialMessage, context); } readIfNeeded(context); }
/// <summary> /// Called when [task completed]. /// </summary> /// <param name="task">The task.</param> /// <param name="result">The result.</param> internal void OnTaskCompleted(IScheduledTask task, TaskResult result) { EventHelper.QueueEventIfNotNull(TaskCompleted, task, new GenericEventArgs <TaskResult> { Argument = result }, Logger); ExecuteQueuedTasks(); }
protected override void DoClose() { var promise = _connectPromise; if (promise != null) { // Use TrySetException() instead of SetException() to avoid the race against cancellation due to timeout. promise.TrySetException(ClosedChannelException.Instance); _connectPromise = null; } var cancellationTask = _connectCancellationTask; if (cancellationTask != null) { cancellationTask.Cancel(); _connectCancellationTask = null; } var readOp = _readOperation; if (readOp != null) { readOp.Dispose(); _readOperation = null; } var writeOp = _writeOperation; if (writeOp != null) { writeOp.Dispose(); _writeOperation = null; } }
/// <summary> /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. /// </summary> /// <param name="scheduledTask">The scheduled task.</param> /// <param name="applicationPaths">The application paths.</param> /// <param name="taskManager">The task manager.</param> /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> /// <exception cref="System.ArgumentNullException"> /// scheduledTask /// or /// applicationPaths /// or /// taskManager /// or /// jsonSerializer /// or /// logger /// </exception> public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger) { if (scheduledTask == null) { throw new ArgumentNullException("scheduledTask"); } if (applicationPaths == null) { throw new ArgumentNullException("applicationPaths"); } if (taskManager == null) { throw new ArgumentNullException("taskManager"); } if (jsonSerializer == null) { throw new ArgumentNullException("jsonSerializer"); } if (logger == null) { throw new ArgumentNullException("logger"); } ScheduledTask = scheduledTask; ApplicationPaths = applicationPaths; TaskManager = taskManager; JsonSerializer = jsonSerializer; Logger = logger; ReloadTriggerEvents(true); }
public ScheduledTaskExecution(IScheduledTask scheduledTask, int scheduledTaskId, IThreadSafeDataAccess threadSafeDataAccess, ExitStrategy exitStrategy) { _scheduledTaskid = scheduledTaskId; _cSharpScheduledTask = scheduledTask; _threadSafeDataAccess = threadSafeDataAccess; _exitStrategy = exitStrategy; }
/// <summary> /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. /// </summary> /// <param name="scheduledTask">The scheduled task.</param> /// <param name="applicationPaths">The application paths.</param> /// <param name="taskManager">The task manager.</param> /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> /// <exception cref="System.ArgumentNullException"> /// scheduledTask /// or /// applicationPaths /// or /// taskManager /// or /// jsonSerializer /// or /// logger /// </exception> public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem) { if (scheduledTask == null) { throw new ArgumentNullException("scheduledTask"); } if (applicationPaths == null) { throw new ArgumentNullException("applicationPaths"); } if (taskManager == null) { throw new ArgumentNullException("taskManager"); } if (jsonSerializer == null) { throw new ArgumentNullException("jsonSerializer"); } if (logger == null) { throw new ArgumentNullException("logger"); } ScheduledTask = scheduledTask; ApplicationPaths = applicationPaths; TaskManager = taskManager; JsonSerializer = jsonSerializer; Logger = logger; _fileSystem = fileSystem; InitTriggerEvents(); }
protected override void DoClose() { TaskCompletionSource promise = this.connectPromise; if (promise != null) { // Use TrySetException() instead of SetException() to avoid the race against cancellation due to timeout. promise.TrySetException(ClosedChannelException); this.connectPromise = null; } IScheduledTask cancellationTask = this.connectCancellationTask; if (cancellationTask != null) { cancellationTask.Cancel(); this.connectCancellationTask = null; } SocketChannelAsyncOperation readOp = this.readOperation; if (readOp != null) { readOp.Dispose(); this.readOperation = null; } SocketChannelAsyncOperation writeOp = this.writeOperation; if (writeOp != null) { writeOp.Dispose(); this.writeOperation = null; } }
/// <summary> /// Thread Safe. Unregisters a task from the task queue. /// </summary> /// <param name="task">The task to unregister.</param> public static void UnregisterTask(IScheduledTask task) { lock (tasks) { tasks.Remove(task); } }
/// <summary> /// Initializes a new instance of the <see cref="ScheduledTaskWorker" /> class. /// </summary> /// <param name="scheduledTask">The scheduled task.</param> /// <param name="applicationPaths">The application paths.</param> /// <param name="taskManager">The task manager.</param> /// <param name="jsonSerializer">The json serializer.</param> /// <param name="logger">The logger.</param> /// <exception cref="ArgumentNullException"> /// scheduledTask /// or /// applicationPaths /// or /// taskManager /// or /// jsonSerializer /// or /// logger /// </exception> public ScheduledTaskWorker(IScheduledTask scheduledTask, IApplicationPaths applicationPaths, ITaskManager taskManager, IJsonSerializer jsonSerializer, ILogger logger, IFileSystem fileSystem) { if (scheduledTask == null) { throw new ArgumentNullException(nameof(scheduledTask)); } if (applicationPaths == null) { throw new ArgumentNullException(nameof(applicationPaths)); } if (taskManager == null) { throw new ArgumentNullException(nameof(taskManager)); } if (jsonSerializer == null) { throw new ArgumentNullException(nameof(jsonSerializer)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } ScheduledTask = scheduledTask; ApplicationPaths = applicationPaths; TaskManager = taskManager; JsonSerializer = jsonSerializer; Logger = logger; _fileSystem = fileSystem; InitTriggerEvents(); }
private bool DetermineNextDueTime(IScheduledTask task) { // Check conditions and signal for task to be removed if (task.Type == ScheduledTask.TypeNow && task.NumberOfPreviousRuns > 0) { return(false); // mark for deletion } if (task.Type == ScheduledTask.TypeAt && task.NumberOfPreviousRuns > 0) { return(false); // mark for deletion } if (task.Type == ScheduledTask.TypeAfter) { task.Due = AddInterval(task).ToDateTimeUtc(); return(task.NumberOfPreviousRuns < 1); } if (task.Type == ScheduledTask.TypeEvery) { task.Due = AddInterval(task).ToDateTimeUtc(); if (task.Repeated != 0) { return(task.NumberOfPreviousRuns < task.Repeated); } } if (task.Type == ScheduledTask.TypeEveryStartingAt) { task.Due = AddInterval(task).ToDateTimeUtc(); } return(true); }
public void RemoveScheduledTask(IScheduledTask scheduledTask) { Argument.IsNotNull(() => scheduledTask); lock (_lock) { Log.Debug("Removing scheduled task {0}", scheduledTask); var removedAnything = false; for (var i = 0; i < _scheduledTasks.Count; i++) { if (ReferenceEquals(scheduledTask, _scheduledTasks[i])) { _scheduledTasks.RemoveAt(i--); removedAnything = true; } } if (removedAnything) { UpdateTimerForNextEvent(); } } }
void Initialize(IChannelHandlerContext context) { // Avoid the case where destroy() is called before scheduling timeouts. // See: https://github.com/netty/netty/issues/143 switch (_state) { case 1: case 2: return; } _state = 1; InitOutputChanged(context); _lastReadTime = _lastWriteTime = Ticks(); if (_readerIdleTime.Ticks > 0) { _readerIdleTimeout = Schedule(context, ReadTimeoutAction, this, context, _readerIdleTime); } if (_writerIdleTime.Ticks > 0) { _writerIdleTimeout = Schedule(context, WriteTimeoutAction, this, context, _writerIdleTime); } if (_allIdleTime.Ticks > 0) { _allIdleTimeout = Schedule(context, AllTimeoutAction, this, context, _allIdleTime); } }
private void AddScheduledTask(IScheduledTask scheduledTask) { if (this.CalculateNextExecutionTime(scheduledTask)) { this.scheduledTasks.TryAdd(scheduledTask.Id, scheduledTask); } }
public virtual CancellationTokenSource schedule(S source, Action task, long delayMillis) { IScheduledExecutorService thread = associations[source]; IScheduledTask tt = thread.Schedule(task, TimeSpan.FromMilliseconds(delayMillis)); return(null); }
/// <summary> /// Waits until one of the tasks represented by <see cref="taskHandles"/> is finished, all remaining task will be aborted. /// </summary> /// <param name="taskHandles">The task handles to wait on.</param> /// <returns></returns> public static int WaitAny(params ITaskHandle[] taskHandles) { //FIXME: The is broken, we should return if a scheduled task is finished not ignore it. // create wait handle array int maxLength = taskHandles.Length; var scheduledTasks = new IScheduledTask[maxLength]; int index = 0; for (int i = 0; i < maxLength; i++) { var scheduledTask = taskHandles[i] as IScheduledTask; if(scheduledTask != null) { if(!scheduledTask.IsFinished) { scheduledTasks[index] = scheduledTask; index++; } } else { throw new InvalidOperationException(String.Format("Couldn't convert task handle \"{0}\" to a IScheduledTask.", taskHandles[i])); } } int length = index; var waitHandles = new WaitHandle[index]; for (int i = 0; i < length; i++) { waitHandles[i] = scheduledTasks[i].FinishedHandle; } int releasedIndex = WaitHandle.WaitAny(waitHandles); // release resources for (int i = 0; i < index; i++) { scheduledTasks[i].Close(); } return releasedIndex; }
/// <summary> /// Changes the frequency for a task that is already managed by this scheduler /// </summary> /// <param name="task">The task to update</param> /// <param name="frequency">The task's desired frequency</param> public void ChangeFrequency(IScheduledTask task, uint frequency) { Assert.IsFalse(frequency == 0, string.Format("TaskScheduler.ChangeFrequency: Frequency for task '{0}' must be greater than 0", task)); // remove and re-add task to recalculate phase RemoveTask(task); AddTask(task, frequency); }
public ScheduledTaskWorker(ITaskRepository taskRepository, IScheduledTask scheduledTask, ITaskManager taskManager) { _taskRepository = taskRepository; ScheduledTask = scheduledTask; _taskManager = taskManager; InitTriggerEvents(); }
private void HandlePingResp() { if (pingRespTimeout != null) { pingRespTimeout.Cancel(); pingRespTimeout = null; } }
/// <summary> /// Adds a task to the priority queue. As no priority value has /// been given, the scheduler will use the delegate in /// TaskPriorityAlgorithm to determine a priority for the task. /// /// Failure to set TaskPriorityAlgorithm ahead of time will /// throw an exception. /// </summary> /// <param name="task">The task to add to the scheduler.</param> public void AddTask(IScheduledTask task) { if (this.TaskPriorityAlgorithm == null) throw new InvalidOperationException("Must set TaskPriorityAlgorithm before using " + "the default AddTask function. Use the 2-argument form instead."); this.AddTask(this.TaskPriorityAlgorithm(task), task); }
public RunningTask(IScheduledTask scheduledTask, DateTime started) { Argument.IsNotNull(() => scheduledTask); ScheduledTask = scheduledTask; Started = started; CancellationTokenSource = new CancellationTokenSource(); }
/// <summary> /// Removes a task from the scheduler. Is a fail-safe function; /// will not throw an exception if the task was not there to /// begin with. /// </summary> /// <param name="task">The task to remove from the scheduler.</param> /// <returns>True if the task was removed, false otherwise.</returns> public Boolean RemoveTask(IScheduledTask task) { if (tasks.Contains(task) == false) { return(false); } tasks.Remove(task); return(true); }
public SchedulerTaskWrapper( CrontabSchedule schedule, IScheduledTask task, DateTime nextRunTime) { Schedule = schedule; this.Task = task; NextRunTime = nextRunTime; }
public HostedService(IScheduledTask scheduledTask) { _taskToExecute = scheduledTask; UnobservedTaskException = (sender, args) => { System.IO.File.WriteAllText(System.IO.Directory.GetCurrentDirectory() + "ErrorReport.txt", System.DateTime.Now + "\t" + args.Exception.Message); args.SetObserved(); }; }
private void startTimer(IEventLoop eventLoop) { timer = eventLoop.Schedule(async() => { timeout += 5; await Action(OriginalPacket); startTimer(eventLoop); }, TimeSpan.FromSeconds(timeout)); }
protected internal virtual void RunTask(IScheduledTask t) { var task = (ScheduledTask)t; if (!task.IsReferenceAlive) { InternalTasks.Remove(task); return; } if (!t.Owner.IsAlive) { return; } if (task.StartTime != null && task.StartTime > DateTime.UtcNow) { return; } if (task.EndTime != null && task.EndTime < DateTime.UtcNow) { task.EndTime = DateTime.UtcNow; RemoveTask(task); { return; } } if (task.Period != null && task.LastRunTime != null && DateTime.UtcNow - task.LastRunTime < task.Period) { return; } try { } catch (Exception ex) { Container.Resolve <ILogger>().LogError("An exception occured in task: " + task.Name, ex); task.EndTime = DateTime.UtcNow; RemoveTask(task); return; } if (task.ExecutionTarget == ExecutionTargetContext.NextFrame || task.ExecutionTarget == ExecutionTargetContext.NextPhysicsUpdate || task.ExecutionTarget == ExecutionTargetContext.Async || task.ExecutionTarget == ExecutionTargetContext.NextAsyncFrame || task.ExecutionTarget == ExecutionTargetContext.Sync) { task.EndTime = DateTime.UtcNow; RemoveTask(task); } }
/// <summary> /// 更新计划任务 /// </summary> public void Update(int taskId, IScheduledTask newTask, string name, string comment) { using (IBlazeDatabase db = DbFactory.GetDatabase()) { try { db.BeginTrans(); SecurityManager sm = AdminServer.TheInstance.SecurityManager; FSEyeObject taskObject = sm.Get(taskId); taskObject.Name = name; taskObject.Comment = comment; sm.Set(taskObject, db); newTask.SecurityObject = taskObject; using (MemoryStream taskDataStream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(taskDataStream, newTask); byte[] taskData = taskDataStream.ToArray(); DataSet ds = new DataSet(); IBlazeTable scheduledTaskTable = db.GetTable(TableString.ScheduledTaskTableName); scheduledTaskTable.Get(ds); DataTable table = ds.Tables[TableString.ScheduledTaskTableName]; DataRow[] rows = table.Select(TableString.ScheduledTaskFieldId + "=" + newTask.SecurityObject.Id); if (rows.Length > 0) { DataRow row = rows[0]; row[TableString.ScheduledTaskFieldTaskData] = taskData; scheduledTaskTable.Set(table); } } foreach (ScheduledTaskUnit unit in _taskList) { if (unit.Task.SecurityObject.Id == taskId) { unit.AvoidCheckTimeout = 0; unit.Task = newTask; break; } } db.CommitTrans(); } catch (Exception ex) { if (db != null) { db.RollbackTrans(); } throw ex; } } }
/// <summary> /// Thread Safe. Registers a new scheduled task to be run every step. /// </summary> /// <param name="task">The task to schedule.</param> public static void RegisterTask(IScheduledTask task) { lock (tasks) { if (!tasks.Contains(task)) { tasks.Add(task); } } }
//Executes a scheduled task asynchronously private void RunTask(IScheduledTask task) { if (!task.IsRunning) { Task.Run(() => { task.Run(); }); } }
/// <summary> /// Register a scheduled task. /// </summary> /// <param name="task">The task to be scheduled.</param> /// <param name="period">The period in seconds to wait between the tasks are run. This is not an exact time period, but /// it should be considered at least + best effort. If set to zero or negative, the system will try to execute the task /// as many times as possible.</param> public void ScheduleTask(IScheduledTask task, int period) { if (task == null) return; taskList.Add(new ScheduledTaskInfo() { Task = task, ScheduledTimePeriod = period }); taskRunner.TaskListChanged(); }
public void AddTask(IScheduledTask task) { task.LastExecuteTime = DateTime.Now; task.LastCompleteTime = DateTime.Now; lock (_tasks) { if (_tasks.Contains(task)) { Logger.Error("Cannot add task " + task + ", it is already there"); } else { _tasks.Add(task); } } }
void Destroy() { this.state = 2; if (this.readerIdleTimeout != null) { this.readerIdleTimeout.Cancel(); this.readerIdleTimeout = null; } if (this.writerIdleTimeout != null) { this.writerIdleTimeout.Cancel(); this.writerIdleTimeout = null; } if (this.allIdleTimeout != null) { this.allIdleTimeout.Cancel(); this.allIdleTimeout = null; } }
/// <summary> /// 添加计划任务 /// </summary> public void Add(IScheduledTask task, string name, string comment) { if (task == null) throw new ArgumentNullException("task"); if (name == null) throw new ArgumentNullException("name"); if (comment == null) throw new ArgumentNullException("comment"); using (IBlazeDatabase db = DbFactory.GetDatabase()) { try { db.BeginTrans(); SecurityManager sm = AdminServer.TheInstance.SecurityManager; FSEyeObject newObject = sm.Get(SecurityObject.FullPath + SecurityManager.ObjectPathDelimiter + name, db); byte[] automationData = AdminServer.TheInstance.AutomationManager.Save(task.Automation); MemoryStream taskDataStream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(taskDataStream, task); byte[] taskData = taskDataStream.ToArray(); if (newObject != null && automationData != null && taskData != null) { newObject.Comment = comment; sm.Set(newObject); task.SecurityObject = newObject; IBlazeTable scheduledTaskTable = db.GetTable(TableString.ScheduledTaskTableName); DataSet ds = new DataSet(); scheduledTaskTable.Get(ds); DataTable table = ds.Tables[TableString.ScheduledTaskTableName]; DataRow row = table.NewRow(); row[TableString.ScheduledTaskFieldId] = newObject.Id; row[TableString.ScheduledTaskFieldTaskData] = taskData; table.Rows.Add(row); scheduledTaskTable.Set(table); ScheduledTaskUnit unit = new ScheduledTaskUnit(); unit.Task = task; unit.AvoidCheckTimeout = 0; _taskList.Add(unit); //设置权限 AdminServer.TheInstance.SecurityManager.CopyAce(newObject.Parent, newObject, true); db.CommitTrans(); } } catch (Exception) { db.RollbackTrans(); } } }
/// <summary> /// 更新计划任务 /// </summary> public void Update(int taskId, IScheduledTask newTask, string name, string comment) { using (IBlazeDatabase db = DbFactory.GetDatabase()) { try { db.BeginTrans(); SecurityManager sm = AdminServer.TheInstance.SecurityManager; FSEyeObject taskObject = sm.Get(taskId); taskObject.Name = name; taskObject.Comment = comment; sm.Set(taskObject, db); newTask.SecurityObject = taskObject; using (MemoryStream taskDataStream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(taskDataStream, newTask); byte[] taskData = taskDataStream.ToArray(); DataSet ds = new DataSet(); IBlazeTable scheduledTaskTable = db.GetTable(TableString.ScheduledTaskTableName); scheduledTaskTable.Get(ds); DataTable table = ds.Tables[TableString.ScheduledTaskTableName]; DataRow[] rows = table.Select(TableString.ScheduledTaskFieldId + "=" + newTask.SecurityObject.Id); if (rows.Length > 0) { DataRow row = rows[0]; row[TableString.ScheduledTaskFieldTaskData] = taskData; scheduledTaskTable.Set(table); } } foreach (ScheduledTaskUnit unit in _taskList) { if (unit.Task.SecurityObject.Id == taskId) { unit.AvoidCheckTimeout = 0; unit.Task = newTask; break; } } db.CommitTrans(); } catch (Exception ex) { if (db != null) db.RollbackTrans(); throw ex; } } }
public void RemoveTask(IScheduledTask task) { if (!tasks.Any(t => t.Task == task)) throw new ArgumentException("Cannot find specified task to delete", "task"); var taskToRemove = tasks.First(t => t.Task == task); tasks.Remove(taskToRemove); }
internal ThreadTask(IScheduledTask task, ManualResetEvent doneEvent) { this.Task = task; this.DoneEvent = doneEvent; }
private DateTime GetNextTimeToRun(IScheduledTask task) { switch (task.IntervalType) { case IntervalTypes.Never: case IntervalTypes.Once: return task.StartTime; case IntervalTypes.Periodic: return task.StartTime < DateTime.UtcNow - task.Interval ? DateTime.UtcNow + task.Interval : (task.StartTime <= DateTime.UtcNow ? task.StartTime + task.Interval : task.StartTime); default: throw new ArgumentException("Invalid interval type given", "task"); } }
public void AddTask(IScheduledTask task) { if (task.TaskAction == null) throw new ArgumentException("Task action cannot be null", "task"); if (tasks.Any(t => t.Task == task)) throw new ArgumentException("Cannot add duplicated task", "task"); tasks.Add(new ScheduledTaskInternal { Task = task, NextTimeToRun = GetNextTimeToRun(task), Enabled = true }); UpdateTimer(); }
/// <summary> /// Removes a task from the scheduler. Is a fail-safe function; /// will not throw an exception if the task was not there to /// begin with. /// </summary> /// <param name="task">The task to remove from the scheduler.</param> /// <returns>True if the task was removed, false otherwise.</returns> public Boolean RemoveTask(IScheduledTask task) { if (tasks.Contains(task) == false) return false; tasks.Remove(task); return true; }
/// <summary> /// Adds a task to the scheduler with the specified priority. /// </summary> /// <param name="priority">The current task's priority for scheduling.</param> /// <param name="task">The task to be queued.</param> public void AddTask(Int32 priority, IScheduledTask task) { this.RemoveTask(task); priorityList.Add(priority, task); }
private void Destroy() { state = 2; if(this.timeoutTask != null) { this.timeoutTask.Cancel(); this.timeoutTask = null; } }
private void Initialize(IChannelHandlerContext context) { switch(this.state) { case 1: case 2: return; } this.state = 1; this.lastReadTime = TimeUtil.GetSystemTime(); if (this.timeout.Ticks > 0) { this.timeoutTask = context.Executor.Schedule(ReadTimeoutAction, this, context, this.timeout); } }
/// <summary> /// Adds a task to the scheduler. /// </summary> /// <param name="task">The task to add to the scheduler.</param> public void AddTask(IScheduledTask task) { tasks.Add(task); }
public void ScheduleRealtimeTask(IScheduledTask task) { ScheduleTask(task, 0); }
/// <summary> /// Remove a task from the scheduler. This is a fail-safe function; it will /// not throw an exception if the task is not in the scheduler. Note that this /// function only removes the first occasion of a task; if you have accidentally /// registered the same task multiple times, it only removes one. /// </summary> /// <param name="task">The task to remove.</param> /// <returns>True if removed, false otherwise.</returns> public Boolean RemoveTask(IScheduledTask task) { Int32 foo = priorityList.IndexOfValue(task); if (foo > -1) { priorityList.Remove(foo); return true; } return false; }
/// <summary> /// Thread Safe. Registers a new scheduled task to be run every step. /// </summary> /// <param name="task">The task to schedule.</param> public static void RegisterTask(IScheduledTask task) { lock (tasks) { if (!tasks.Contains(task)) tasks.Add(task); } }
public void RemoveScheduledTask(IScheduledTask scheduledTask) { Argument.IsNotNull(() => scheduledTask); lock (_lock) { Log.Debug("Removing scheduled task {0}", scheduledTask); var removedAnything = false; for (int i = 0; i < _scheduledTasks.Count; i++) { if (ReferenceEquals(scheduledTask, _scheduledTasks[i])) { _scheduledTasks.RemoveAt(i--); removedAnything = true; } } if (removedAnything) { UpdateTimerForNextEvent(); } } }
public void AddScheduledTask(IScheduledTask scheduledTask) { Argument.IsNotNull(() => scheduledTask); lock (_lock) { Log.Debug("Adding scheduled task {0}", scheduledTask); _scheduledTasks.Add(scheduledTask); UpdateTimerForNextEvent(); } }
private bool StartTask(IScheduledTask scheduledTask) { lock (_lock) { if (!IsEnabled) { return false; } Log.Debug("Starting task {0}", scheduledTask); var runningTask = new RunningTask(scheduledTask, _timeService.CurrentDateTime); #pragma warning disable 4014 // Note: don't await, we are a scheduler. var task = TaskShim.Run(async () => await scheduledTask.InvokeAsync(), runningTask.CancellationTokenSource.Token); task.ContinueWith(OnRunningTaskCompleted); #pragma warning restore 4014 Log.Debug("Started task {0}", scheduledTask); var completed = task.IsCompleted; if (completed) { // Shortcut mode TaskStarted.SafeInvoke(this, new TaskEventArgs(runningTask)); OnRunningTaskCompleted(task); } else { _runningTasks.Add(new RunningTaskInfo(task, runningTask)); TaskStarted.SafeInvoke(this, new TaskEventArgs(runningTask)); } } // Note: it's important to start possible recurring tasks outside the loop if (scheduledTask.Recurring.HasValue) { var startDate = _timeService.CurrentDateTime.Add(scheduledTask.Recurring.Value); Log.Debug("Task {0} is a recurring task, rescheduling a copy at '{1}'", scheduledTask, startDate); var newScheduledTask = (IScheduledTask)scheduledTask.Clone(); newScheduledTask.Start = startDate; AddScheduledTask(newScheduledTask); } return true; }