支持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);
            }
        }
    }
posted @ 2020-03-10 17:27  .Neterr  阅读(1534)  评论(1编辑  收藏  举报