Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Windows-service
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
Posted 14-Feb-11 19:49pm
Edited 14-Feb-11 19:51pm
JF201552.8K
v2
Comments
Sandeep Mewara at 15-Feb-11 3:49am
   
It would be good if you add what issue you are facing. Just posting the code would not encourage most of users. Any error? Issue?
Aksh@169 at 15-Feb-11 5:44am
   
The issue is that I dont know how to schedule it biweekly at a specific time:(

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 696
1 OriginalGriff 478
2 Tadit Dash 400
3 sanket saxena 337
4 Peter Leow 228
0 Sergey Alexandrovich Kryukov 11,890
1 OriginalGriff 7,335
2 Peter Leow 5,003
3 Abhinav S 3,943
4 Maciej Los 3,575


Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 15 Feb 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid