如何使用计划任务

1.自定义一个类MyMob.cs,处理计划任务清单
2.添加计划任务服务

services.AddScheduleJob();
services.AddSingleton<MyJob>();

3.启动计划任务
注入自定义类MyJob

myJob.Start();

自定义任务实例

1.自定义类MyJob 继承 ScheduleJob
2.重写方法CustomJobAsync(),自定义要启动的任务 ,可定义多个

实例代码

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RsCode;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    public class MyJob : ScheduleJob
    {
        private readonly IBackgroundTaskQueue _taskQueue;
        private readonly ILogger _logger;
        private readonly CancellationToken _cancellationToken;
        public MyJob(IBackgroundTaskQueue taskQueue, ILogger<ScheduleJob> logger, IHostApplicationLifetime applicationLifetime)
        {
            _taskQueue = taskQueue;
            _logger = logger;
            _cancellationToken = applicationLifetime.ApplicationStopping;
        }



        public override async ValueTask CustomJobAsync()
        {
            while (!_cancellationToken.IsCancellationRequested)
            {
                var keyStroke = Console.ReadKey();

                if (keyStroke.Key == ConsoleKey.Spacebar)
                {
                    // Enqueue a background work item
                    await _taskQueue.QueueWorkItemAsync(BuildWorkItem);
                }

                if(keyStroke.Key==ConsoleKey.R)
                {
                    await _taskQueue.QueueWorkItemAsync(BuildWorkItem2);
                }
            }
        }

        private async ValueTask BuildWorkItem(CancellationToken token)
        {
            // Simulate three 5-second tasks to complete
            // for each enqueued work item

            int delayLoop = 0;
            var guid = Guid.NewGuid().ToString();

            _logger.LogInformation("Queued Background Task {Guid} is starting.", guid);

            while (!token.IsCancellationRequested && delayLoop < 3)
            {
                try
                {
                    await Task.Delay(TimeSpan.FromSeconds(5), token);
                }
                catch (OperationCanceledException)
                {
                    // Prevent throwing if the Delay is cancelled
                }

                delayLoop++;

                _logger.LogInformation("Queued Background Task {Guid} is running. "
                                       + "{DelayLoop}/3", guid, delayLoop);
            }

            if (delayLoop == 3)
            {
                _logger.LogInformation("Queued Background Task {Guid} is complete.", guid);
            }
            else
            {
                _logger.LogInformation("Queued Background Task {Guid} was cancelled.", guid);
            }
        }

        private async ValueTask BuildWorkItem2(CancellationToken token)
        { 
            _logger.LogInformation("BuildWorkItem2");
        }
    }
}

3.添加计划任务服务

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");

        using var host = Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddSchedulerJob(ctx =>
            {
                if (!int.TryParse(hostContext.Configuration["QueueCapacity"], out var queueCapacity))
                    queueCapacity = 100;
                return new BackgroundTaskQueue(queueCapacity);
            });

            services.AddSingleton<MyJob>();
        })
        .Build();

        host.StartAsync().GetAwaiter().GetResult();

        var myJob = host.Services.GetRequiredService<MyJob>();
        myJob.Start();

        host.WaitForShutdownAsync().GetAwaiter().GetResult();
    }
}