如何在.netcore的网站中加入定时器服务

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Threading;
namespace RobotManagementWeb.Jobs
{
    public class JobExcuter : BackgroundService
    {
        private readonly ILogger<JobExcuter> _logger;
        public JobExcuter(ILogger<JobExcuter> logger)
        {
            _logger = logger;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

            while (!stoppingToken.IsCancellationRequested)
            {
                await new TaskFactory().StartNew(() =>
                {
                    try
                    {
                        //满足某种条件执行 比如每天凌晨执行
                        var time = DateTime.Now.ToString("HH:mm:ss");
                        if ("06:00:00" == time)
                        {
                            JobDatabase.JobChatInfoShrink();
                            _logger.LogError("定时删除:成功");
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.LogError("定时删除异常:失败-" + e.Message);
                    }

                    //定时任务休眠
                    Thread.Sleep(1 * 1000);
                });
            }
        }

    }
}

然后 需要在我们可以在做一个静态方法,用来定制执行,如果需要使用数据库的话,请仿照下面的方式

using System;
using System.Linq;
using DAL;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace RobotManagementWeb.Jobs
{
    public class JobDatabase
    {
        public static IConfiguration Configuration { get; set; }
        //private readonly flowDataContext _flowcontext;
        public static void JobChatInfoShrink()
        {
            //配置configaration
            var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddEnvironmentVariables();
            Configuration = builder.Build();
            //获取数据库上下文
            var flowconnectionString = Configuration.GetConnectionString("FlowConnection");
            Microsoft.EntityFrameworkCore.DbContextOptionsBuilder<flowDataContext> option = new Microsoft.EntityFrameworkCore.DbContextOptionsBuilder<flowDataContext>();
            MySqlDbContextOptionsExtensions.UseMySql(option, flowconnectionString);
            var _flowcontext= new flowDataContext(option.Options);
            //这里就可以随意使用上下文来操作数据库


               
            

        }
    }
}

最后在startup.cs中的ConfigureServices里注册下

//定时任务的注入
//services.AddTransient<Microsoft.Extensions.Hosting.IHostedService, Job>();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值