You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中停止Quartz Scheduler任务执行?求可行方案

解决方案

1. 确保Job实现IInterruptableJob接口

Quartz的Interrupt()方法仅对实现了IInterruptableJob接口的Job生效,你的Job类必须实现该接口并编写中断逻辑,示例代码:

public class TargetJob : IInterruptableJob
{
    private volatile bool _isInterrupted = false;

    public Task Execute(IJobExecutionContext context)
    {
        while (!_isInterrupted)
        {
            // 执行任务核心逻辑
            await Task.Delay(500);
        }
        return Task.CompletedTask;
    }

    public Task Interrupt()
    {
        _isInterrupted = true;
        return Task.CompletedTask;
    }
}

2. 仅中断正在执行的目标组Job

你当前代码会中断group1下所有Job,但只有正在运行的Job需要中断。结合GetCurrentlyExecutingJobs()筛选目标任务:

IScheduler scheduler = await _factory.GetScheduler();
var executingJobs = await scheduler.GetCurrentlyExecutingJobs();

// 过滤出group1中正在执行的Job
var targetJobs = executingJobs
    .Where(ctx => ctx.JobDetail.Key.Group == "group1")
    .Select(ctx => ctx.JobDetail.Key)
    .ToList();

foreach (var jobKey in targetJobs)
{
    await scheduler.Interrupt(jobKey);
}

// 强制关闭调度器,不等待剩余任务完成
await scheduler.Shutdown(true);

3. 先校验调度器状态

操作前确认调度器处于运行状态,否则中断和关闭操作会无效:

IScheduler scheduler = await _factory.GetScheduler();
if (!scheduler.IsStarted)
{
    await scheduler.Shutdown();
    return;
}

// 后续中断逻辑...

4. 捕获中断异常

Interrupt可能抛出不支持中断、持久化失败等异常,建议添加捕获处理:

foreach (var jobKey in targetJobs)
{
    try
    {
        await scheduler.Interrupt(jobKey);
    }
    catch (UnsupportedOperationException)
    {
        Console.WriteLine($"Job {jobKey.Name}不支持中断操作");
    }
    catch (JobPersistenceException ex)
    {
        Console.WriteLine($"中断Job {jobKey.Name}失败: {ex.Message}");
    }
}

内容的提问来源于stack exchange,提问作者Dx Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:40:27