Search code examples
aspnetboilerplate

How to cancel BackgroundJob or let a newjob don't retry?


my case similar the example, a user presses a 'report' button to start a long-running reporting job. You add this job to the queue and send the report's result to your user via email when it's completed. But, I don't need retries job execution when the job failed. I want job stop and send notification. And can cancel on service.

        public void CancelAllMyJob()
        {
            var jobs = backgroundJobStore.GetWaitingJobsAsync(int.MaxValue).Result.Where(o => o.JobType.Contains(nameof(MyJob))).ToList();
            if (jobs.Count > 0)
            {
                foreach (BackgroundJobInfo job in jobs)
                {
                    backgroundJobStore.DeleteAsync(job).Wait();
                }
            }
        }
        public async Task StartMyJob(MyJobInput input)
        {
            MyJobArgs args = new MyJobArgs
            {
                TenantId = AbpSession.TenantId,
                UserId = AbpSession.UserId.Value,
            };
            var id = await backgroundJobManager.EnqueueAsync<MyJob, MyJobArgs >(args);
            (await backgroundJobStore.GetAsync(Convert.ToInt64(id))).TryCount = 0;
        }

Solution

  •     public async Task StartMyJob(MyJobInput input)
                {
                    MyJobArgs args = new MyJobArgs
                    {
                        TenantId = AbpSession.TenantId,
                        UserId = AbpSession.UserId.Value,
                    };
                    await Task.Run(() =>
                    {
                        using (var uow = UnitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
                        {
                            myJob.Execute(args);
                        }
                    });
        }
    

    It's work, thanks!