.net croe实现windows定时服务

1、App.config中配置连接字符串和定时信息

<connectionStrings>
    <add name="ERPTOOL" connectionString="Data Source=localhost;User Id=sa;Password=126.com;"/>
</connectionStrings>
<appSettings>
    <add key="EmailJob" value="20.48.30"/>
    <add key="CronScheduleJob" value="0 48 08 * * ? *"/>
    <add key="CronInsertJob" value="0 48 08 * * ? *"/>
</appSettings>

2、程序入口Program.cs

using Quartz;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;
using MailpushService.common;

namespace FcrEmailService
{
    class Program
    {
        static void Main()
        {
            var baseaddr = AppContext.BaseDirectory;
            var rc = HostFactory.Run(x =>
            {
                x.Service<Service>(s =>
                {
                    s.ConstructUsing(name => new Service());
                    s.WhenStarted(tc => tc.Start());
                    s.WhenStopped(tc => tc.Stop());
                });
                x.RunAsLocalSystem();
                Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Information()
                    .WriteTo.Console()
                    .WriteTo.File(baseaddr + $"\\logs\\TempImportLog.txt", rollingInterval: RollingInterval.Day)
                    .CreateLogger();
                x.UseSerilog(Log.Logger);

                x.SetDescription("FrcEmailService" + "离子风机运行数据邮件推送服务");
                x.SetDisplayName("FrcEmailService");
                x.SetServiceName("FrcEmailService");
            });

            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
            Environment.ExitCode = exitCode;

            // 调试使用
            //var test = new EmailJob();
            //var test = new InsertFanData();
            //test.Run();

        }
    }
}

3、配置服务信息

using log4net;
using Quartz;
using Quartz.Impl;
using Serilog;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace FcrEmailService
{
    public class Service
    {
        private readonly IScheduler scheduler;
         public Service()
        {
            NameValueCollection props = new NameValueCollection
            {
               { "quartz.serializer.type", "binary" },
               { "quartz.scheduler.instanceName", "TempImportScheduler" },
               { "quartz.jobStore.type", "Quartz.Simpl.RAMJobStore, Quartz" },
               { "quartz.threadPool.threadCount", "20" }
            };
            StdSchedulerFactory factory = new StdSchedulerFactory(props);
            scheduler = factory.GetScheduler().ConfigureAwait(false).GetAwaiter().GetResult();
        }
public void Start()
        {
            Log.Information("Fcr数据推送] " + "  服务启动");
            scheduler.Start().ConfigureAwait(false).GetAwaiter().GetResult();
            startjob();
        }
        public void startjob()
        {
            IJobDetail job1 = JobBuilder.Create<EmailJob>()
                  .WithIdentity("JobName1", "JobGroup1")
                  .Build();
            ITrigger trigger1 = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                 .WithCronSchedule(ConfigurationManager.AppSettings["CronScheduleJob"].ToString())
                .Build();
             scheduler.ScheduleJob(job1, trigger1).ConfigureAwait(false).GetAwaiter().GetResult();

            IJobDetail job2 = JobBuilder.Create<InsertFanData>()
                  .WithIdentity("JobName2", "JobGroup2")
                  .Build();
            ITrigger trigger2 = TriggerBuilder.Create()
                .WithIdentity("trigger2", "group2")
                 .WithCronSchedule(ConfigurationManager.AppSettings["CronScheduleJob1"].ToString())
                .Build();
            scheduler.ScheduleJob(job2, trigger2).ConfigureAwait(false).GetAwaiter().GetResult();
        }
        public void Stop()
        {
            scheduler.Shutdown().ConfigureAwait(false).GetAwaiter().GetResult();
        }
    }
}

4、配置数据库连接信息DBConnection

using log4net;
using System;
using System.Configuration;
using System.Data.SqlClient;

namespace FrcEmailService
{
    public class DBConnection
    {
        rivate readonly ILog _logger = LogManager.GetLogger(typeof(DBConnection));
        string connectionStr = "";
        public SqlConnection GetSqlConnection(string Connstr) {
             string connectionStr = "";
            if (Connstr == "DctDBZhuHai")
            {
                 connectionStr = ConfigurationManager.ConnectionStrings["DctDBZhuHai"].ConnectionString;
            }
            try
            {
                SqlConnection sqlcon = new SqlConnection(connectionStr);
                return sqlcon;
            }
            catch (Exception e)
            {
                _logger.Info("传入字符:" + Connstr + "数据库字符:" + connectionStr + " 出错了\n" + e.Message.ToString() + "\n");
                throw e;
            }
            
        }
    }
}

5、接口开发代码common文件夹下的common.cs文件

using Dapper; 
using log4net; 
using Newtonsoft.Json; 
using OfficeOpenXml; u
sing System; 
using System.Collections.Generic; 
using System.Data; 
using System.IO; 
using System.Linq; 
namespace FcrEmailService.common 
{ 
    public class common
    {
         DBConnection dbconn = new DBConnection(); 
         private readonly ILog _logger = LogManager.GetLogger(typeof(EmailJob));

        // 获取基地、分厂、车间数据 
        public dynamic GetworkshopData() 
        { 
            string sqlstring = ""; 
            sqlstring = @"select * from WORKSHOP_INFO"; 
            var result = dbconn.GetSqlConnection("DctDBZhuHai").Query<dynamic>(sqlstring).ToList(); 
            DataTable ERPDataTable = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result), typeof(DataTable)); 
            return ERPDataTable; 
        }

    }
}

 6、应用程序

using Dapper;
using log4net;
using MailpushService.common;
using Newtonsoft.Json;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Configuration;
using System.IO;

namespace FcrEmailService
{
    public class EmailJob : IJob
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(EmailJob));
        EmailHelper emailHelper = new EmailHelper();

        public Task Execute(IJobExecutionContext context)
        {
            Run();
            return Task.FromResult(true);
        }

        public void Run() 
        {
            // 程序逻辑
            DataTable resultWeek = common1.GetEmailSettingData(0);
        }

    }
}

  • 1
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:深蓝海洋 设计师:CSDN官方博客 返回首页
评论

打赏作者

土豆丶杨

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值