public override void Init(CommandContext commandContext)
        {
            // clean additional data related to this job
            IJobHandler jobHandler = JobHandler;

            jobHandler?.OnDelete(JobHandlerConfiguration, this);

            //cancel the retries -> will resolve job incident if present
            Retries = commandContext.ProcessEngineConfiguration.DefaultNumberOfRetries;

            //delete the job's exception byte array and exception message
            string exceptionByteArrayIdToDelete = null;

            if (ExceptionByteArrayId != null)
            {
                exceptionByteArrayIdToDelete = ExceptionByteArrayId;
                this.ExceptionByteArrayId    = null;
                this.exceptionMessage        = null;
            }
            //clean the lock information
            LockOwner          = null;
            LockExpirationTime = null;

            if (exceptionByteArrayIdToDelete != null)
            {
                //ByteArrayEntity byteArray = commandContext.GetDbEntityManager<ByteArrayEntity>().getDbEntityManager().selectById(ByteArrayEntity.class, exceptionByteArrayIdToDelete);
                var byteArray = commandContext.GetDbEntityManager <ResourceEntity>().Get(exceptionByteArrayIdToDelete);
                commandContext.GetDbEntityManager <ResourceEntity>().Delete(byteArray);
            }
        }
Beispiel #2
0
        private async Task ProcessJob()
        {
            _switch.SetStateAction(DoNothing);

            if (!_jobHandler.IsCompleted())
            {
                var heartbeat =
                    await Try.Do(() =>
                                 _krakerApi.SendAgentStatus(_agentId, _jobHandler.GetJobDescription()),
                                 e =>
                {
                    _logger.Warning("Can't sent the status: {0}", e);
                    return(WorkStatus.Continue);
                });

                if (heartbeat.Status == Constants.WorkStatuses.Stop)
                {
                    _logger.Information("The job is canceled");
                    _jobHandler.Cancel();
                }

                _switch.SetStateAction(ProcessJob);
                return;
            }

            await _jobHandler.Finish();

            _jobHandler = _incorrectJobHandler;
            _switch.SetStateAction(WaitJob);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="UploadDataSourceFileJob"/> class.
        /// </summary>
        /// <param name="handler">Injected hangfire job handler</param>
        public UploadDataSourceFileJob(
            IJobHandler <UploadDataSourceFileJob> handler)
        {
            Argument.NotNull(handler, nameof(handler));

            _handler = handler;
        }
Beispiel #4
0
 public EntityFactory(
     GUIDManager guidManager,
     INeedHandler needHandler,
     IObjectIconHandler objectIconHandler,
     ICultureHandler cultureHandler,
     IEntitySexualityHandler sexualityHandler,
     IEntityBioSexHandler sexHandler,
     IGenderHandler genderHandler,
     IEntityRomanceHandler romanceHandler,
     IJobHandler jobHandler,
     IPhysicsManager physicsManager,
     IEntitySkillHandler skillHandler,
     IDerivedValueHandler derivedValueHandler,
     RNG roller)
 {
     this.GuidManager         = guidManager;
     this.Roller              = roller;
     this.NeedHandler         = needHandler;
     this.ObjectIcons         = objectIconHandler;
     this.CultureHandler      = cultureHandler;
     this.SexualityHandler    = sexualityHandler;
     this.BioSexHandler       = sexHandler;
     this.JobHandler          = jobHandler;
     this.RomanceHandler      = romanceHandler;
     this.GenderHandler       = genderHandler;
     this.PhysicsManager      = physicsManager;
     this.SkillHandler        = skillHandler;
     this.DerivedValueHandler = derivedValueHandler;
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="CleanFolderJob"/> class.
        /// </summary>
        /// <param name="handler">Injected job handler</param>
        public CleanFolderJob(
            IJobHandler <CleanFolderJob> handler)
        {
            Argument.NotNull(handler, nameof(handler));

            _handler = handler;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="UploadIntegrationImportJob"/> class.
        /// </summary>
        /// <param name="handler">Job handler</param>
        public UploadIntegrationImportJob(
            IJobHandler <UploadIntegrationImportJob> handler)
        {
            Argument.NotNull(handler, nameof(handler));

            _handler = handler;
        }
Beispiel #7
0
 public EventProcessor(IEventHandlerFactory eventHandlerFactory, IJobHandler jobHandler,
                       IActionDispatcher actionDispatcher)
 {
     _eventHandlerFactory = eventHandlerFactory;
     _jobHandler          = jobHandler;
     _actionDispatcher    = actionDispatcher;
 }
Beispiel #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DownloadIntegrationExportJob"/> class.
        /// </summary>
        /// <param name="handler">Injected job handler</param>
        public DownloadIntegrationExportJob(
            IJobHandler <DownloadIntegrationExportJob> handler)
        {
            Argument.NotNull(handler, nameof(handler));

            _handler = handler;
        }
Beispiel #9
0
        /// <summary>
        /// 异步执行任务 把任务插入线程任务队列中排队执行
        /// </summary>
        /// <param name="jobInfo"></param>
        /// <param name="jobHandler"></param>
        /// <returns></returns>
        private async Task AsyncExecuteJob(JobRunRequest jobInfo, IJobHandler jobHandler)
        {
            Func <object, Task> action = async(state) =>
            {
                if (jobInfo.JobStatus == JobStatus.Killed)  //已终止的任务 就不要再运行了
                {
                    _logger.LogInformation($"**************该任务已被终止 {jobInfo.jobId},{jobInfo.logId}********************");
                    return;
                }

                jobInfo.SetRunning();
                ReturnT executeResult = null;
                try
                {
                    executeResult = await jobHandler.Execute(new JobExecuteContext(jobInfo.logId, jobInfo.executorParams));
                }
                catch (Exception ex)
                {
                    executeResult = ReturnT.Failed(ex.StackTrace + "————" + ex.Message);
                    _logger.LogError(ex, "xxljob执行任务错误");
                }

                _xxlJobExecutor.RemoveJobInfo(jobInfo);
                await CallBack(jobInfo.logId, executeResult);  //这里保证一定要回调结果 不然就要重试了(配置了重试次数),这里回调为失败结果也会重试(配置了重试次数)
            };

            _xxlJobExecutor.RegistJobInfo(jobInfo);
            //插入任务执行队列中 根据jobid路由到固定线程中 保证同一个jobid串行执行
            _taskExecutor.GetSingleThreadTaskExecutor(jobInfo.jobId).Execute(action, null);
            await Task.CompletedTask;
        }
Beispiel #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SwallowExceptionJobHandlerDecorator{T}"/> class.
        /// </summary>
        public SwallowExceptionJobHandlerDecorator(
            IJobHandler <T> handler) : base(handler)
        {
            Argument.NotNull(handler, nameof(handler));

            _handler = handler;
        }
Beispiel #11
0
 public EventDispatcher(IEventStore eventStore,
                        IJobHandler jobHandler,
                        IEventQueue eventQueue)
 {
     _eventStore = eventStore;
     _jobHandler = jobHandler;
     _eventQueue = eventQueue;
 }
Beispiel #12
0
        protected IJobHandler ResolveJobHandler()
        {
            IJobHandler jobHandler = Context.ProcessEngineConfiguration.JobHandlers[jobHandlerType];

            EnsureUtil.EnsureNotNull("Cannot find job handler '" + jobHandlerType + "' from job '" + this + "'", "jobHandler", jobHandler);

            return(jobHandler);
        }
Beispiel #13
0
 public CommandProcessor(ICommandHandlerFactory commandHandlerFactory,
                         IEventDispatcher eventDispatcher,
                         IJobHandler jobHandler)
 {
     _commandHandlerFactory = commandHandlerFactory;
     _eventDispatcher       = eventDispatcher;
     _jobHandler            = jobHandler;
 }
Beispiel #14
0
        public JobThread(int jobId, IJobHandler handler)
        {
            this.jobId   = jobId;
            this.handler = handler;

            this.triggerQueue    = new BlockingCollection <TriggerParam>();// new BlockingCollection<TriggerParam>();
            this.triggerLogIdSet = new ConcurrentHashSet <int>();
        }
Beispiel #15
0
 public EventDispatcher(IEventStore eventStore,
                        IJobHandler jobHandler,
                        IEventProcessor eventProcessor)
 {
     _eventStore     = eventStore;
     _jobHandler     = jobHandler;
     _eventProcessor = eventProcessor;
 }
Beispiel #16
0
 public Scheduler(
     [NotNull] IStateSynchronizer synchronizer,
     [NotNull] IFlowController controller,
     [NotNull] IJobWaiter jobWaiter,
     [NotNull] IJobHandler jobHandler)
 {
     this.synchronizer = synchronizer;
     this.controller   = controller;
     this.jobWaiter    = jobWaiter;
     this.jobHandler   = jobHandler;
 }
Beispiel #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="LogJobHandlerDecorator{T}"/> class.
        /// </summary>
        /// <param name="handler">Injected job handler</param>
        /// <param name="logger">Injected application logger</param>
        public LogJobHandlerDecorator(
            IJobHandler <T> handler,
            IApplicationLogger logger) : base(handler)
        {
            Argument.NotNull(handler, nameof(handler));
            Argument.NotNull(logger, nameof(logger));

            _handler = handler;

            _logger = logger;
        }
Beispiel #18
0
        public IJobHandlerManage AddJobHandler(string jobhandlerName, IJobHandler jobHandler)
        {
            var key = jobhandlerName.ToLower();

            if (_jobHandlers.ContainsKey(key))
            {
                throw new Exception($"JobHandlerAttrbute配置重复,{jobHandler.GetType().FullName}");
            }
            _jobHandlers.TryAdd(key, jobHandler);
            return(this);
        }
Beispiel #19
0
 public void Subscribe(EventType type, IJobHandler handler)
 {
     _subscribers.AddOrUpdate(type, new List <IJobHandler>(10), (key, list) =>
     {
         var index = list.FindIndex(m => m == handler);
         if (index == -1)
         {
             list.Add(handler);
         }
         return(list);
     });
 }
Beispiel #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="jobEntity"></param>
        protected internal virtual void ExecuteJobHandler(IJobEntity jobEntity)
        {
            IExecutionEntity execution = null;

            if (!(jobEntity.ExecutionId is null))
            {
                execution = ExecutionEntityManager.FindById <ExecutionEntityImpl>(jobEntity.ExecutionId);
            }

            IDictionary <string, IJobHandler> jobHandlers = processEngineConfiguration.JobHandlers;
            IJobHandler jobHandler = jobHandlers[jobEntity.JobHandlerType];

            jobHandler.Execute(jobEntity, jobEntity.JobHandlerConfiguration, execution, CommandContext);
        }
Beispiel #21
0
        public Agent(IJobHandlerProvider jobHandlerProvider,
                     IAgentIdManager agentIdManager,
                     IKrakerApi krakerApi,
                     ILogger logger)
        {
            _switch             = new FiniteStateMachine(WaitJob);
            _jobHandlerProvider = jobHandlerProvider;
            _krakerApi          = krakerApi;
            _logger             = logger;
            _agentId            = agentIdManager.GetCurrent().Id
                                  ?? throw new InvalidOperationException("The agent needs to have id");

            var incorrectJobHandler = new IncorrectJobHandler(new IncorrectJob("Haven't got any jobs"));

            _jobHandler          = incorrectJobHandler;
            _incorrectJobHandler = incorrectJobHandler;
        }
Beispiel #22
0
        private async Task WaitJob()
        {
            _switch.SetStateAction(DoNothing);

            var job = await _krakerApi.GetJob(_agentId);

            _logger.Information("Got a job {0}", job);

            if (job == null || job is IncorrectJob or DoNothingJob)
            {
                _switch.SetStateAction(WaitJob);
                return;
            }

            _jobHandler = _jobHandlerProvider.Get(job);

            _jobHandler.Execute();
            _switch.SetStateAction(ProcessJob);
        }
Beispiel #23
0
        public void TestSetup()
        {
            synchronizer = Substitute.For <IStateSynchronizer>();

            controller = Substitute.For <IFlowController>();
            controller.ShouldStillOperateOn(Arg.Any <SchedulerState>()).Returns(true, true, true, true, false); // 2 iterations

            completedTask1 = Task.FromResult(true);
            completedTask2 = Task.FromResult(true);

            jobWaiter = Substitute.For <IJobWaiter>();
            jobWaiter
            .WaitForNextCompletedJob(Arg.Any <SchedulerState>())
            .Returns(completedTask1, completedTask2);

            jobHandler = Substitute.For <IJobHandler>();

            scheduler = new Hercules.Client.Sink.Scheduler.Scheduler(synchronizer, controller, jobWaiter, jobHandler);
        }
Beispiel #24
0
        public static JobThread registJobThread(int jobId, IJobHandler handler, String removeOldReason)
        {
            JobThread newJobThread = new JobThread(jobId, handler);

            newJobThread.start();
            logger.Info(string.Format(">>>>>>>>>>> xxl-job regist JobThread success, jobId:{0}, handler:{1}", jobId, handler));


            //JobThread oldJobThread
            JobThreadRepository.TryGetValue(jobId, out JobThread oldJobThread);

            if (oldJobThread != null)
            {
                oldJobThread.toStop(removeOldReason);
                //oldJobThread.interrupt();
            }

            JobThreadRepository.TryAdd(jobId, newJobThread);

            return(newJobThread);
        }
Beispiel #25
0
        public virtual void Execute(CommandContext commandContext)
        {
            if (ExecutionId != null)
            {
                ExecutionEntity exec = Execution;
                EnsureUtil.EnsureNotNull("Cannot find execution with id '" + ExecutionId + "' referenced from job '" + this + "'", "execution", exec);
            }

            // initialize activity id
            GetActivityId();

            // increment sequence counter before job execution
            IncrementSequenceCounter();

            PreExecute(commandContext);
            IJobHandler jobHandler = JobHandler;
            IJobHandlerConfiguration configuration = JobHandlerConfiguration;

            EnsureUtil.EnsureNotNull("Cannot find job handler '" + JobHandlerType + "' from job '" + this + "'", "jobHandler", jobHandler);
            jobHandler.Execute(configuration, execution, commandContext, TenantId);
            PostExecute(commandContext);
        }
Beispiel #26
0
        public virtual void Delete(bool incidentResolved)
        {
            //throw new NotImplementedException();
            CommandContext commandContext = Context.CommandContext;

            IncrementSequenceCounter();

            // clean additional data related to this job
            IJobHandler jobHandler = JobHandler;

            if (jobHandler != null)
            {
                jobHandler.OnDelete(JobHandlerConfiguration, this);
            }

            // fire delete event if this job is not being executed
            bool executingJob = this.Equals(commandContext.CurrentJob);

            commandContext.JobManager.DeleteJob(this, !executingJob);

            // Also delete the job's exception byte array
            if (ExceptionByteArrayId != null)
            {
                commandContext.ByteArrayManager.DeleteByteArrayById(ExceptionByteArrayId);
            }

            // remove link to execution
            ExecutionEntity execution = Execution;

            if (execution != null)
            {
                execution.RemoveJob(this);
            }

            RemoveFailedJobIncident(incidentResolved);
        }
Beispiel #27
0
 public ActionDispatcher(ICommandStore commandStore, ICommandQueue commandQueue, IJobHandler jobHandler)
 {
     _commandStore = commandStore;
     _commandQueue = commandQueue;
     _jobHandler   = jobHandler;
 }
Beispiel #28
0
 public void SetUp()
 {
     GlobalConstants.ActionLog = new ActionLog();
     this.abilityHandler       = new AbilityHandler();
     this.target = new JobHandler(this.abilityHandler, new RNG());
 }
Beispiel #29
0
 public static IJobHandler registJobHandler(String name, IJobHandler jobHandler)
 {
     logger.Info(string.Format(">>>>>>>>>>> xxl-job register jobhandler success, name:{0}, jobHandler:{1}", name, jobHandler));
     return(jobHandlerRepository.GetOrAdd(name, jobHandler));
 }
Beispiel #30
0
 public JobController(IJobService service, IJobHandler handler)
 {
     _service = service;
     _handler = handler;
 }