安排Windows服务每周通过C#代码运行两次 [英] Schedule Windows Service to run twice a week through C# code

查看:125
本文介绍了安排Windows服务每周通过C#代码运行两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在研究如何每周三(例如星期二和星期五)下午3点运行Windows服务.

请在下面的代码中找到并建议如何实现

Hi,

I am figuring out how to run my Windows Service twice a week(say on Tuesday and Friday)at 3 pm.

Please find below the code and suggest how can I implement it

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;
using System.Net.Mail;
using System.Configuration;
using System.Collections;
using System.Reflection;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
namespace AutomationProcess
{
    public partial class Service1 : ServiceBase
    {
        // DateTime lastRun = DateTime.Now;

        public Service1()
        {
            InitializeComponent();
        }
        public void automate()
        {
            string filepath, filename, fileExcel;
            string ReportCount = "select count(rs.contactID) from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546)";
            string UserCount = "select count(distinct(rs.contactID)) from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546)";
            Random nRandom = new Random(DateTime.Now.Millisecond);
            //Create a random file name.
            fileExcel = "t" + nRandom.Next().ToString() + ".xls";
            filepath = "C:\\test";
            filename = filepath + "\\" + fileExcel;
            try
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.AppSettings["Connection"];
                SqlCommand cmd = new SqlCommand("select rs.contactID,SurveyType,ModuleName,LogDate from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546) order by LogDate ", conn);
                SqlCommand cmd1 = new SqlCommand(ReportCount, conn);
                SqlCommand cmd2 = new SqlCommand(UserCount, conn);
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(cmd);
                DataSet d = new DataSet();
                mySqlDataAdapter.Fill(d, "dataset");
                conn.Open();
                string reports = Convert.ToString(cmd1.ExecuteScalar());
                string users = Convert.ToString(cmd2.ExecuteScalar());
                ---------------------------some tasks to do-----------------------------
                
            }
            SendEmail(ReportCount, UserCount);
        }
        private static void WriteToLog(string message)
        {
            using (var fl = new StreamWriter("c:\\test\\test.log", true))
            {
                fl.WriteLine(message);
            }
        }

        private static void SendEmail(string reports, string users)
        {
            string filepath = "C:\\test";
            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = new MailAddress("lmn@poc.com");
                message.To.Add("xyz@abc.com");
                message.Subject = "Statistical Report";
                message.Body = "Please find attached the statistical report " +
                     "\nTotal number of reports downloaded by users is " + reports +
                     "\nTotal number of users who have downloaded reports is " + users;
                Attachment attach = new Attachment(filepath + @"\test.xlsx");
                WriteToLog("Mail check");
                message.Attachments.Add(attach);
                WriteToLog("Attached excel");
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost");
                WriteToLog("Checking SMTP");
                smtp.Send(message);

            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message);
                // Console.WriteLine(ex.ToString());
            }
        }

        protected override void OnStart(string[] args)
        {
            // WriteToLog("Calling Automate");
            //automate(); 
            //return;
            DateTime startTime;
            startTime = DateTime.Now;
            System.Timers.Timer time = new System.Timers.Timer();
            //Assuming that the service is started at 1 pm and mail needs to be sent at 4pm which makes the time interval=3hours
            time.Interval = 3*60*60*1000;
            time.Elapsed += new ElapsedEventHandler(time_Elapsed);
            //string startTimeString = ConfigurationManager.AppSettings["Interval"].ToString();
            
            time.Enabled = true;
        }


        void time_Elapsed(object sender, ElapsedEventArgs e)
        {
           DateTime startTime = DateTime.Now;
           string newStartTime;
            if ((startTime.Day == 2 || startTime.Day == 5))
             {
            automate();
             }
            newStartTime = ConfigurationManager.AppSettings["Interval"].ToString();
              
            //DateTime small = new DateTime();
            //DateTime large = new DateTime();
        }
        protected override void OnStop()
        {
        }

    }
}





谢谢





Thanks

推荐答案

我建​​议您为此使用Quartz.Net.它是一个开放源代码框架.此外,它最适合小型到大型项目.

您可以在Quartz.Net上找到更多信息,
1. http://quartznet.sourceforge.net/tutorial/lesson_1.html [ http://blog.goyello.com /2009/09/21/how-to-use-quartz-net-in-pro-way/ [
I would suggetst you to use Quartz.Net for this. It is an open source framework. Moreover it is best suited for small to big projects.

You can find more information on Quartz.Net at
1 . http://quartznet.sourceforge.net/tutorial/lesson_1.html[^]
2. http://blog.goyello.com/2009/09/21/how-to-use-quartz-net-in-pro-way/[^]

Hope this helps.
All the best.


这篇关于安排Windows服务每周通过C#代码运行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆