Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

怎么确保一个任务只运行一个实例 #55

Closed
yus1977 opened this issue Jan 26, 2021 · 5 comments
Closed

怎么确保一个任务只运行一个实例 #55

yus1977 opened this issue Jan 26, 2021 · 5 comments

Comments

@yus1977
Copy link

yus1977 commented Jan 26, 2021

配置周期任务时,如果任务时间长,周期较短。比如:周期时间为10秒,任务执行时间为30秒。
这会导致前一个周期的任务还没有结束,后一个周期的任务就启动了。
怎么才能确保前一个周期的任务没有结束前,后面的任务不会启动。

@yus1977
Copy link
Author

yus1977 commented Jan 26, 2021

不想在任务里再实现锁功能,能不能在创建任务时就配置。

@hey-hoho
Copy link
Owner

你说的这种情况应该不会存在,程序里限制了上一次没有执行完是不会执行下一次的,再观察看看

@yus1977
Copy link
Author

yus1977 commented Jan 27, 2021

我基于示例里的 TaskCancel 修改了一下, 在循环里加了 Sleep

    public class TaskCancel : TaskBase
    {
        public override void Run(TaskContext context)
        {
            Task.Run(() =>
            {
                while (true)
                {
                    context.WriteLog($"当前时间是:{DateTime.Now}");
                    if (CancellationToken.IsCancellationRequested)
                    {
                        context.WriteLog("[IsCancellationRequested: true]我要终止运行运行了~",Base.Dto.LogCategory.Warn);
                        break;
                    }
                    System.Threading.Thread.Sleep(new Random().Next(6000, 10000));
                    System.Diagnostics.Debug.WriteLine($"{System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()} : {Guid.NewGuid().ToString()}");
                }
            });
        }
    }

然后创建一个任务,每5秒执行它一次。结果就出现前面说的情况了。

@hey-hoho
Copy link
Owner

Task.Run已经转到后台线程池去运行了,对于系统来说本次任务执行已经完成。

@yus1977
Copy link
Author

yus1977 commented Jan 27, 2021

明白了,就是说,Run里面的方法不能使用异步,异步不能确保任务唯一性。

@yus1977 yus1977 closed this as completed Jan 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants