支持Cron表达式、间隔时间的工具(TaskScheduler)


后台任务如何支持间隔时间、Cron表达式两种方式?
分享一个项目TaskScheduler,这是我从Furion项目中拷出来的

源码:https://gitee.com/dot-net-core/task-scheduler.git

开始

间隔时间后台服务

    public class IntervalBackgroundService : BackgroundService
    {
        private readonly ILogger<IntervalBackgroundService> _logger = null;
        public IntervalBackgroundService(ILogger<IntervalBackgroundService> logger)
        {
            _logger = logger;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                await SpareTime.DoAsync(1000, () =>
                {
                    _logger.LogInformation("Interval Worker running at: {time}", DateTimeOffset.Now);
                }, stoppingToken);
            }
        }
    }

Cron表达式后台服务

    public class CronBackgroundService : BackgroundService
    {
        private readonly ILogger<CronBackgroundService> _logger = null;
        public CronBackgroundService(ILogger<CronBackgroundService> logger)
        {
            _logger = logger;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                // 执行 Cron 表达式任务
                await SpareTime.DoAsync("*/5 * * * * *", () =>
                {
                    _logger.LogInformation("Cron Worker running at: {time}", DateTimeOffset.Now);
                }, stoppingToken, CronFormat.IncludeSeconds);
            }
        }
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM