Ejemplo n.º 1
0
        /// <summary>
        /// 添加作业
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        public async Task <AjaxResponse> AddJob(TaskOptions taskOptions)
        {
            try
            {
                (bool success, string errorMsg)validExpression = IsValidExpression(taskOptions.Interval);
                if (!validExpression.success)
                {
                    return(new AjaxResponse(false, validExpression.errorMsg));
                }
                bool existTask = await _task.Exists(taskOptions.TaskName, taskOptions.GroupName);

                if (existTask)
                {
                    return(new AjaxResponse(false, $"作业:{taskOptions.TaskName},分组:{taskOptions.GroupName}已经存在"));
                }

                await _task.Add(taskOptions);

                //TODO:如果失败删除数据库数据
                await AddSchedulerJob(taskOptions);

                _ = _log.WriteLog($"新增任务{taskOptions.TaskName}--{taskOptions.GroupName}");
            }
            catch (Exception ex)
            {
                _logger.LogError("添加作业错误", ex);
                return(new AjaxResponse(false, ex.Message));
            }
            return(new AjaxResponse());
        }
Ejemplo n.º 2
0
        public async Task StartQuartz()
        {
            int         errorCount            = 0;
            string      errorMsg              = "";
            TaskOptions options               = null;
            IEnumerable <TaskOptions> allTask = await _task.GetAll();

            try
            {
                foreach (TaskOptions item in allTask)
                {
                    options = item;
                    await AddSchedulerJob(item);
                }
            }
            catch (Exception ex)
            {
                errorCount = +1;
                errorMsg  += $"作业:{options?.TaskName},异常:{ex.Message}";
                _logger.LogError("启动作业错误", ex);
            }
            string content = $"成功:{ allTask.Count() - errorCount}个,失败{errorCount}个,异常:{errorMsg}";

            _ = _log.WriteLog(content);
        }
Ejemplo n.º 3
0
            public TaskHandler(AsyncContextOperation operation, TaskOptions options)
            {
                _operation = operation;
                _options   = options;
                _endStep   = (int)States.RunningMain;
                if (options.HasFlag(TaskOptions.Cancel))
                {
                    _endStep |= (int)(States.Cancelling | States.RunningExtent);
                }
                else if (options.HasFlag(TaskOptions.Extent))
                {
                    _endStep |= (int)States.RunningExtent;
                }

                if (_operation._state > _endStep)
                {
                    var(isError, isCancel) = GetResult(_operation._state, _endStep, _options);
                    _syncResult            = isError ? Task.FromException(operation._error)
                                                : isCancel?Task.FromCanceled(_operation._ct.Token)
                                                 : Task.CompletedTask;

                    _asyncResult = default;
                    _ended       = true;
                }
                else
                {
                    _syncResult  = default;
                    _asyncResult = new TaskCompletionSource <object>();
                    _ended       = false;
                }
            }
Ejemplo n.º 4
0
        public static object ModifyTaskEntity(this TaskOptions taskOptions, ISchedulerFactory schedulerFactory,
                                              JobAction action)
        {
            TaskOptions options = null;
            object      result  = null;

            switch (action)
            {
            case JobAction.除:
                for (var i = 0; i < _taskList.Count; i++)
                {
                    options = _taskList[i];
                    if (options.TaskName == taskOptions.TaskName && options.GroupName == taskOptions.GroupName)
                    {
                        _taskList.RemoveAt(i);
                    }
                }

                break;

            case JobAction.修改:
                options = _taskList
                          .FirstOrDefault(x => x.TaskName == taskOptions.TaskName && x.GroupName == taskOptions.GroupName);
                //移除以前的配置
                if (options != null)
                {
                    _taskList.Remove(options);
                }

                //生成任务并添加新配置
                result = taskOptions.AddJob(schedulerFactory).GetAwaiter().GetResult();
                break;

            case JobAction.暂停:
            case JobAction.开启:
            case JobAction.停止:
            case JobAction.立即执行:
                options = _taskList
                          .FirstOrDefault(x => x.TaskName == taskOptions.TaskName && x.GroupName == taskOptions.GroupName);
                if (action == JobAction.暂停)
                {
                    options.Status = (int)TriggerState.Paused;
                }
                else if (action == JobAction.停止)
                {
                    options.Status = (int)action;
                }
                else
                {
                    options.Status = (int)TriggerState.Normal;
                }
                break;
            }

            //生成配置文件
            FileQuartz.WriteJobConfig(_taskList);
            FileQuartz.WriteJobAction(action, taskOptions.TaskName, taskOptions.GroupName,
                                      "操作对象:" + JsonConvert.SerializeObject(taskOptions));
            return(result);
        }
Ejemplo n.º 5
0
        protected override bool PerformPrequisites()
        {
            // build editor
            BuildTarget Command = new BuildTarget();

            Command.ProjectName = ProjectFile != null?ProjectFile.GetFileNameWithoutAnyExtensions() : null;

            Command.Platforms = BuildHostPlatform.Current.Platform.ToString();
            Command.Targets   = "Editor";
            Command.NoTools   = false;

            if (Command.Execute() != ExitCode.Success)
            {
                return(false);
            }

            // if they want a hot DDC then do the test one time with no timing
            if (TaskOptions.HasFlag(DDCTaskOptions.HotDDC))
            {
                RunEditorAndWaitForMapLoad(true);
            }

            base.PerformPrequisites();

            return(true);
        }
Ejemplo n.º 6
0
        private async Task AddSchedulerJob(TaskOptions taskOptions)
        {
            IJobDetail job = _jobManager.GetJob(null)
                             .WithIdentity(taskOptions.TaskName, taskOptions.GroupName)
                             .Build();
            ITrigger trigger = _triggerManager.Create(null)
                               .StartNow()
                               .WithIdentity(taskOptions.TaskName, taskOptions.GroupName)
                               .WithDescription(taskOptions.Describe)
                               .WithCronSchedule(taskOptions.Interval)
                               .Build();
            IScheduler scheduler = await _schedulerFactory.GetScheduler();

            scheduler.JobFactory = _jobFactory;
            await scheduler.ScheduleJob(job, trigger);

            if (taskOptions.Status == (int)TriggerState.Normal)
            {
                await scheduler.Start();
            }
            else
            {
                await Pause(taskOptions);

                _ = _log.WriteLog($"作业:{taskOptions.TaskName},分组:{taskOptions.GroupName},新建时未启动原因,状态为:{taskOptions.Status}");
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// 获取任务
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public static TaskOptions GetTaskOptions(this IJobExecutionContext context)
 {
     var _taskList = TaskRepository.GetTaskList();
     AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
     TaskOptions taskOptions = _taskList.Where(x => x.name == trigger.Name && x.group_name == trigger.Group).FirstOrDefault();
     return taskOptions ?? _taskList.Where(x => x.name == trigger.JobName && x.group_name == trigger.JobGroup).FirstOrDefault();
 }
Ejemplo n.º 8
0
 public RemarkerTaskOptionsPage()
 {
     this.profileManager = new ProfileManager();
     this.service        = this.profileManager.Service;
     this.model          = new TaskOptions();
     this.isActivated    = false;
 }
Ejemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>通过作业上下文获取作业对应的配置参数
        /// <returns></returns>
        public static TaskOptions GetTaskOptions(this IJobExecutionContext context)
        {
            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
            TaskOptions     taskOptions = _taskList.Where(x => x.TaskName == trigger.Name && x.GroupName == trigger.Group).FirstOrDefault();

            return(taskOptions ?? _taskList.Where(x => x.TaskName == trigger.JobName && x.GroupName == trigger.JobGroup).FirstOrDefault());
        }
Ejemplo n.º 10
0
        async Task ExecuteHttp(TaskOptions taskOptions)
        {
            DateTime            dateTime = DateTime.Now;
            HttpResponseMessage httpMessage;
            HttpClient          client = _clientFactory.CreateClient("api");

            if (!string.IsNullOrEmpty(taskOptions.AuthKey) &&
                !string.IsNullOrEmpty(taskOptions.AuthValue))
            {
                client.DefaultRequestHeaders.Add(taskOptions.AuthKey.Trim(), taskOptions.AuthValue.Trim());
            }

            if (taskOptions.RequestType == RequestTypeEnum.Get)
            {
                httpMessage = await client.GetAsync(taskOptions.ApiUrl);
            }
            else
            {
                httpMessage = await client.PostAsync(taskOptions.ApiUrl, null);
            }
            TaskLog taskLog = new TaskLog()
            {
                ExecutionDuration = DateTime.Now.Subtract(dateTime).Milliseconds,
                ExecutionTime     = dateTime,
                Msg           = await httpMessage.Content.ReadAsStringAsync(),
                TaskId        = taskOptions.Id,
                TaskLogStatus = httpMessage.IsSuccessStatusCode ? TaskLogStatusEnum.Success : TaskLogStatusEnum.Fail
            };

            _ = _taskLogService.WriteLog(taskLog);
            _ = _taskService.UpdateLastRunTime(taskOptions.Id);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 添加作业
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <param name="schedulerFactory"></param>
        /// <param name="init">是否初始化,否=需要重新生成配置文件,是=不重新生成配置文件</param>
        /// <returns></returns>
        public static async Task <object> AddJob(this TaskOptions taskOptions, ISchedulerFactory schedulerFactory, bool init = false)
        {
            try
            {
                //元组用于验证CRON表达式是否正确
                (bool, string)validExpression = taskOptions.Interval.IsValidExpression();
                if (!validExpression.Item1)
                {
                    return new { status = false, msg = validExpression.Item2 }
                }
                ;

                //元组用于验证作业是否已经存在
                (bool, object)result = taskOptions.Exists(init);
                if (!result.Item1)
                {
                    return(result.Item2);
                }
                if (!init)
                {
                    _taskList.Add(taskOptions);
                    FileQuartz.WriteJobConfig(_taskList);
                }

                IJobDetail job = JobBuilder.Create <HttpResultful>()
                                 .WithIdentity(taskOptions.TaskName, taskOptions.GroupName)
                                 .Build();
                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity(taskOptions.TaskName, taskOptions.GroupName)
                                   .StartNow().WithDescription(taskOptions.Describe)
                                   .WithCronSchedule(taskOptions.Interval)
                                   .Build();
                IScheduler scheduler = await schedulerFactory.GetScheduler();

                await scheduler.ScheduleJob(job, trigger);

                if (taskOptions.Status == (int)TriggerState.Normal)
                {
                    await scheduler.Start();
                }
                else
                {
                    await schedulerFactory.Pause(taskOptions);

                    //TODO:更新日志
                    FileQuartz.WriteStartLog($"作业:{taskOptions.TaskName},分组:{taskOptions.GroupName},新建时未启动原因,状态为:{taskOptions.Status}");
                }
                //TODO:更新动作日志
                if (!init)
                {
                    FileQuartz.WriteJobAction(JobAction.新增, taskOptions.TaskName, taskOptions.GroupName);
                }
            }
            catch (Exception ex)
            {
                return(new { status = false, msg = ex.Message });
            }
            return(new { status = true });
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates a new task under the authenticated account. Makes a POST and a GET request to the Tasks resource.
        /// </summary>
        /// <param name="options">The options for the new task to be created</param>
        public Models.Task CreateTask(TaskOptions options)
        {
            var request = Request("tasks", Method.POST);

            request.AddBody(options);

            return(Execute <Models.Task>(request));
        }
Ejemplo n.º 13
0
        private IRestRequest UpdateTaskRequest(long taskId, TaskOptions options)
        {
            var request = Request("tasks/" + taskId, RestSharp.Method.PUT);

            request.AddBody(options);

            return(request);
        }
Ejemplo n.º 14
0
        private IRestRequest CreateTaskRequest(TaskOptions options)
        {
            var request = Request("tasks", RestSharp.Method.POST);

            request.AddBody(options);

            return(request);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Updates a task on the authenticated account. Makes a PUT and a GET request to the Tasks resource.
        /// </summary>
        /// <param name="taskId">The ID for the task to update</param>
        /// <param name="options">The options to be updated</param>
        public Task <Models.Task> UpdateTaskAsync(long taskId, TaskOptions options)
        {
            var request = Request("tasks/" + taskId, Method.PUT);

            request.AddBody(options);

            return(ExecuteAsync <Models.Task>(request));
        }
Ejemplo n.º 16
0
        private static TaskOptions GetTaskOptions(string name, bool?billableByDefault, bool?isDefault, decimal?defaultHourlyRate)
        {
            var options = new TaskOptions {
                Name = name, BillableByDefault = billableByDefault, IsDefault = isDefault, DefaultHourlyRate = defaultHourlyRate
            };

            return(options);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates a new task under the authenticated account. Makes a POST and a GET request to the Tasks resource.
        /// </summary>
        /// <param name="options">The options for the new task to be created</param>
        public Task CreateTask(TaskOptions options)
        {
            var request = Request("tasks", RestSharp.Method.POST);

            request.AddBody(options);

            return(Execute <Task>(request));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Updates a task on the authenticated account. Makes a PUT and a GET request to the Tasks resource.
        /// </summary>
        /// <param name="taskId">The ID for the task to update</param>
        /// <param name="options">The options to be updated</param>
        public Task UpdateTask(long taskId, TaskOptions options)
        {
            var request = Request("tasks/" + taskId, RestSharp.Method.PUT);

            request.AddBody(options);

            return(Execute <Task>(request));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public async Task Add(TaskOptions task)
        {
            string sql = @"INSERT INTO TaskOptions(TaskName,GroupName,Interval,ApiUrl,AuthKey,AuthValue,Describe,RequestType,LastRunTime,Status)
                        VALUES (@TaskName,@GroupName,@Interval,@ApiUrl,@AuthKey,@AuthValue,@Describe,@RequestType,@LastRunTime,@Status)";

            using var con = new DapperDbContexts().Connection;
            await con.ExecuteAsync(sql, task);
        }
Ejemplo n.º 20
0
        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);
        }
Ejemplo n.º 21
0
        private async Task ExecuteInternal(TaskOptions options)
        {
            // Cancel the current execution, if any
            if (CurrentCancellationTokenSource != null)
            {
                throw new InvalidOperationException("Cannot execute a Task that is already running");
            }

            var progress = new SimpleProgress <double>();

            CurrentCancellationTokenSource = new CancellationTokenSource();

            Logger.Info("Executing {0}", Name);

            ((TaskManager)TaskManager).OnTaskExecuting(this);

            progress.ProgressChanged += progress_ProgressChanged;

            TaskCompletionStatus status;

            CurrentExecutionStartTime = DateTime.UtcNow;

            Exception failureException = null;

            try
            {
                if (options != null && options.MaxRuntimeTicks.HasValue)
                {
                    CurrentCancellationTokenSource.CancelAfter(TimeSpan.FromTicks(options.MaxRuntimeTicks.Value));
                }

                await ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress).ConfigureAwait(false);

                status = TaskCompletionStatus.Completed;
            }
            catch (OperationCanceledException)
            {
                status = TaskCompletionStatus.Cancelled;
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error", ex);

                failureException = ex;

                status = TaskCompletionStatus.Failed;
            }

            var startTime = CurrentExecutionStartTime;
            var endTime   = DateTime.UtcNow;

            progress.ProgressChanged -= progress_ProgressChanged;
            CurrentCancellationTokenSource.Dispose();
            CurrentCancellationTokenSource = null;
            CurrentProgress = null;

            OnTaskCompleted(startTime, endTime, status, failureException);
        }
Ejemplo n.º 22
0
 public static bool UpdateTask(TaskOptions taskOptions)
 {
     using (var conn = new MySqlConnection(Global.MySQLConnection))
     {
         var sql    = "update task set `name`=@name,group_name=@group_name,`interval`=@interval,api_url=@api_url,auth_key=@auth_key,auth_value=@auth_value,`describe`=@describe,request_method=@request_method,last_time=@last_time,`status`=@status where id=@id";
         var result = conn.Execute(sql, taskOptions);
         return(result > 0);
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// 修改任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public async Task Edit(TaskOptions task)
        {
            string sql = @"UPDATE TaskOptions SET TaskName = @TaskName,GroupName = @GroupName,Interval = @Interval
                    ,ApiUrl = @ApiUrl,AuthKey = @AuthKey,AuthValue = @AuthValue,Describe = @Describe,RequestType = @RequestType
                    ,LastRunTime = @LastRunTime,Status = @Status WHERE Id = @Id";

            using var con = new DapperDbContexts().Connection;
            await con.ExecuteAsync(sql, task);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// <para>Loads all <see cref="TaskPlugin"/>s that are not found or enabled in settings</para>
        /// </summary>
        private void Refresh()
        {
            ObservableDictionary <string, bool> plugins = TaskOptions.GetPluginsSetting();

            List <Type> types = new List <Type>(this.TaskPluginsAvailable);

            types = types.FindAll(new Predicate <Type>(item => { return(!plugins.ContainsKey(item.Name) || plugins[item.Name]); }));

            types.ForEach(new Action <Type>(item => loadTask(item)));
        }
Ejemplo n.º 25
0
        protected bool RunEditorAndWaitForMapLoad(bool bIsWarming)
        {
            string ProjectArg = ProjectFile != null?ProjectFile.ToString() : "";

            string EditorPath = HostPlatform.Current.GetUE4ExePath("UE4Editor.exe");
            string LogArg     = string.Format("-log={0}.log", MakeValidFileName(GetFullTaskName()).Replace(" ", "_"));
            string Arguments  = string.Format("{0} {1} -execcmds=\"automation runtest System.Maps.PIE;Quit\" -stdout -FullStdOutLogOutput -unattended {2}", ProjectArg, EditorArgs, LogArg);

            if (TaskOptions.HasFlag(DDCTaskOptions.NoSharedDDC))
            {
                Arguments += (" -ddc=noshared");
            }

            if (!bIsWarming && TaskOptions.HasFlag(DDCTaskOptions.NoShaderDDC))
            {
                Arguments += (" -noshaderddc");
            }

            if (TaskOptions.HasFlag(DDCTaskOptions.NoXGE))
            {
                Arguments += (" -noxgeshadercompile");
            }

            var RunOptions = CommandUtils.ERunOptions.AllowSpew | CommandUtils.ERunOptions.NoWaitForExit;

            var SpewDelegate = new ProcessResult.SpewFilterCallbackType(EndOnMapCheckFilter);

            //TestCompleted = false;
            LastStdOutTime = DateTime.Now;
            CurrentProcess = CommandUtils.Run(EditorPath, Arguments, Options: RunOptions, SpewFilterCallback: SpewDelegate);

            DateTime StartTime = DateTime.Now;

            int MaxWaitMins = 90;

            while (!CurrentProcess.HasExited)
            {
                Thread.Sleep(5 * 1000);

                lock (CurrentProcess)
                {
                    if ((LastStdOutTime - StartTime).TotalMinutes >= MaxWaitMins)
                    {
                        Log.TraceError("Gave up waiting for task after {0} minutes of no output", MaxWaitMins);
                        CurrentProcess.ProcessObject.Kill();
                    }
                }
            }

            int ExitCode = CurrentProcess.ExitCode;

            CurrentProcess = null;

            return(ExitCode == 0);
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> Remove(TaskOptions taskOptions)
        {
            var model = taskOptions.ApiUrl.Split('=')[1].Trim();
            var token = _context.Set <ViewTokens>().Where(item => item.ModelId == model)?.FirstOrDefault();

            token.UpdateTime = DateTime.Now;
            token.IsActive   = false;
            _context.Set <ViewTokens>().Update(token);
            _context.SaveChanges();
            return(Json(await _schedulerFactory.Remove(taskOptions)));
        }
Ejemplo n.º 27
0
 public static bool AddTask(TaskOptions taskOptions)
 {
     using (var conn = new MySqlConnection(Global.MySQLConnection))
     {
         taskOptions.id          = Guid.NewGuid().ToString("N");
         taskOptions.create_time = DateTime.Now;
         var sql    = "insert into task(id,`name`,group_name,`interval`,api_url,auth_key,auth_value,`describe`,request_method,last_time,create_time,`status`) values(@id,@name,@group_name,@interval,@api_url,@auth_key,@auth_value,@describe,@request_method,@last_time,@create_time,@status)";
         var result = conn.Execute(sql, taskOptions);
         return(result > 0);
     }
 }
        /// <summary>
        /// Gets the decrypted configuration data.
        /// </summary>
        /// <returns>A string containing the configuration data. If the data was encrypted, the configuration returned is decrypted.</returns>
        public string GetClearConfiguration()
        {
            TaskOptions options = (TaskOptions)this.Options;

            if (options.HasFlag(TaskOptions.ProtectedConfiguration) && (!string.IsNullOrEmpty(this.EncryptionKeyId)) && (this.GetMediaContext() != null))
            {
                return(ConfigurationEncryptionHelper.DecryptConfigurationString(this.GetMediaContext(), this.EncryptionKeyId, this.InitializationVector, this.Configuration));
            }

            return(this.Configuration);
        }
Ejemplo n.º 29
0
        public Task Execute(IJobExecutionContext context)
        {
            DateTime        dateTime    = DateTime.Now;
            TaskOptions     taskOptions = context.GetTaskOptions();
            string          httpMessage = "";
            AbstractTrigger trigger     = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;

            if (taskOptions == null)
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", "未到找作业或可能被移除", true);
                return(Task.CompletedTask);
            }

            if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
            {
                FileHelper.WriteFile(FileQuartz.LogPath + trigger.Group, $"{trigger.Name}.txt", "未配置url", true);
                return(Task.CompletedTask);
            }

            try
            {
                Dictionary <string, string> header = new Dictionary <string, string>();
                if (!string.IsNullOrEmpty(taskOptions.AuthKey) &&
                    !string.IsNullOrEmpty(taskOptions.AuthValue))
                {
                    header.Add(taskOptions.AuthKey.Trim(), taskOptions.AuthValue.Trim());
                }

                if (taskOptions.RequestType?.ToLower() == "get")
                {
                    httpMessage = HttpManager.HttpGetAsync(taskOptions.ApiUrl, header).Result;
                }
                else
                {
                    httpMessage = HttpManager.HttpPostAsync(taskOptions.ApiUrl, null, null, 60, header).Result;
                }
            }
            catch (Exception ex)
            {
                httpMessage = ex.Message;
            }

            try
            {
                string logContent = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}_{dateTime.ToString("yyyy-MM-dd HH:mm:ss")}_{(string.IsNullOrEmpty(httpMessage)? "OK" : httpMessage)}\r\n";
                FileHelper.WriteFile(FileQuartz.LogPath + taskOptions.GroupName + "\\", $"{taskOptions.TaskName}.txt", logContent, true);
            }
            catch (Exception)
            {
            }
            Console.Out.WriteLineAsync(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + httpMessage);
            return(Task.CompletedTask);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 根据ID获取任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <TaskOptions> GetTaskById(int id)
        {
            string sql = @"SELECT * FROM TaskOptions WHERE Id = @id";

            using var con = new DapperDbContexts().Connection;
            TaskOptions task = await con.QueryFirstOrDefaultAsync <TaskOptions>(sql, new
            {
                id = id
            });

            return(task);
        }
 public static IJob CreateAndSubmitOneTaskJob(CloudMediaContext context, string name, IMediaProcessor mediaProcessor, string preset, IAsset asset, TaskOptions options)
 {
     IJob job = context.Jobs.Create(name);
     job.Priority = InitialJobPriority;
     ITask task = job.Tasks.AddNew("Task1", mediaProcessor, preset, options);
     task.InputAssets.Add(asset);
     task.OutputAssets.AddNew("Output asset", AssetCreationOptions.None);
     DateTime timebeforeSubmit = DateTime.UtcNow;
     job.Submit();
     Assert.AreEqual(1, job.Tasks.Count, "Job contains unexpected amount of tasks");
     Assert.AreEqual(1, job.InputMediaAssets.Count, "Job contains unexpected total amount of input assets");
     Assert.AreEqual(1, job.OutputMediaAssets.Count, "Job contains unexpected total amount of output assets");
     Assert.AreEqual(1, job.Tasks[0].InputAssets.Count, "job.Task[0] contains unexpected amount of input assets");
     Assert.AreEqual(1, job.Tasks[0].OutputAssets.Count, "job.Task[0] contains unexpected amount of output assets");
     Assert.IsFalse(String.IsNullOrEmpty(job.Tasks[0].InputAssets[0].Id), "Asset Id is Null or empty");
     Assert.IsFalse(String.IsNullOrEmpty(job.Tasks[0].OutputAssets[0].Id), "Asset Id is Null or empty");
     return job;
 }
        public void LaunchJobs_OneJobPerInputAssetWithSpecificConfig(IMediaProcessor processor, List<IAsset> selectedassets, string jobname, int jobpriority, string taskname, string outputassetname, List<string> configuration, AssetCreationOptions myAssetCreationOptions, TaskOptions myTaskOptions, string storageaccountname = "")
        {
            // a job per asset, one task per job, but each task has a specific config
            Task.Factory.StartNew(() =>
            {
                int index = -1;

                foreach (IAsset asset in selectedassets)
                {
                    index++;
                    string jobnameloc = jobname.Replace(Constants.NameconvInputasset, asset.Name);
                    IJob myJob = _context.Jobs.Create(jobnameloc, jobpriority);
                    string config = configuration[index];

                    string tasknameloc = taskname.Replace(Constants.NameconvInputasset, asset.Name).Replace(Constants.NameconvAMEpreset, config);
                    ITask myTask = myJob.Tasks.AddNew(
                           tasknameloc,
                          processor,
                          config,
                          myTaskOptions);

                    myTask.InputAssets.Add(asset);

                    // Add an output asset to contain the results of the task
                    string outputassetnameloc = outputassetname.Replace(Constants.NameconvInputasset, asset.Name).Replace(Constants.NameconvAMEpreset, config);
                    if (storageaccountname == "")
                    {
                        myTask.OutputAssets.AddNew(outputassetnameloc, asset.StorageAccountName, myAssetCreationOptions); // let's use the same storage account than the input asset
                    }
                    else
                    {
                        myTask.OutputAssets.AddNew(outputassetnameloc, storageaccountname, myAssetCreationOptions);
                    }


                    // Submit the job and wait until it is completed. 
                    bool Error = false;
                    try
                    {
                        TextBoxLogWriteLine("Job '{0}' : submitting...", jobnameloc);
                        myJob.Submit();
                    }

                    catch (Exception ex)
                    {
                        // Add useful information to the exception
                        TextBoxLogWriteLine("Job '{0}' : problem", jobnameloc, true);
                        TextBoxLogWriteLine(ex);
                        Error = true;
                    }
                    if (!Error)
                    {
                        TextBoxLogWriteLine("Job '{0}' : submitted.", jobnameloc);
                        Task.Factory.StartNew(() => dataGridViewJobsV.DoJobProgress(myJob));
                    }
                    TextBoxLogWriteLine();
                }

                DotabControlMainSwitch(Constants.TabJobs);
                DoRefreshGridJobV(false);

            }

                );
        }
        public void LaunchJobs(IMediaProcessor processor, List<IAsset> selectedassets, string jobname, int jobpriority, string taskname, string outputassetname, List<string> configuration, AssetCreationOptions myAssetCreationOptions, TaskOptions myTaskOptions, string storageaccountname = "")
        {
            foreach (IAsset asset in selectedassets)
            {
                string jobnameloc = jobname.Replace(Constants.NameconvInputasset, asset.Name);
                IJob myJob = _context.Jobs.Create(jobnameloc, jobpriority);
                foreach (string config in configuration)
                {
                    string tasknameloc = taskname.Replace(Constants.NameconvInputasset, asset.Name).Replace(Constants.NameconvAMEpreset, config);
                    ITask myTask = myJob.Tasks.AddNew(
                           tasknameloc,
                          processor,
                          config,
                          myTaskOptions);

                    myTask.InputAssets.Add(asset);

                    // Add an output asset to contain the results of the task
                    string outputassetnameloc = outputassetname.Replace(Constants.NameconvInputasset, asset.Name).Replace(Constants.NameconvAMEpreset, config);
                    if (storageaccountname == "")
                    {
                        myTask.OutputAssets.AddNew(outputassetnameloc, asset.StorageAccountName, myAssetCreationOptions); // let's use the same storage account than the input asset
                    }
                    else
                    {
                        myTask.OutputAssets.AddNew(outputassetnameloc, storageaccountname, myAssetCreationOptions);
                    }
                }


                // Submit the job and wait until it is completed. 
                try
                {
                    myJob.Submit();
                }
                catch (Exception e)
                {
                    // Add useful information to the exception
                    if (selectedassets.Count < 5)  // only if 4 or less jobs submitted
                    {
                        MessageBox.Show(string.Format("There has been a problem when submitting the job '{0}'", jobnameloc) + Constants.endline + Constants.endline + Program.GetErrorMessage(e), "Job Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    // Add useful information to the exception
                    TextBoxLogWriteLine("There has been a problem when submitting the job {0}.", jobnameloc, true);
                    TextBoxLogWriteLine(e);
                    return;
                }
                TextBoxLogWriteLine("Job '{0}' submitted.", jobnameloc);
                Task.Factory.StartNew(() => dataGridViewJobsV.DoJobProgress(myJob));
            }
            DotabControlMainSwitch(Constants.TabJobs);
            DoRefreshGridJobV(false);
        }