Menu ▼


Running service in custom scheduled time

In our previous article we have seen how to run the service in continuous time intervals. In this article we will see how to run the service in more customized schedule timings.

In this example we are taking the schedule, by reading the text file "Schedule.txt". and we are considering that the first line of the schedule file will contains hours in coma separated format and second line will contains minutes in coma separated format. and the service has to run in the given hours and minutes.

Schedule.txt
10,12,15,17
5,6,7,10,14,15


Code:
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.IO;

namespace WindowsServiceExample
{
    public partial class Service1 : ServiceBase
    {

        System.Timers.Timer serviceTimer = null;
        string fileLocation = "C:\\servicelog.txt";

        public Service1()
        {
            InitializeComponent();
            serviceTimer = new System.Timers.Timer();
            serviceTimer.Elapsed += new System.Timers.ElapsedEventHandler(serviceTimer_Elapsed);
            serviceTimer.Interval = 1 * 60 * 1000;
            serviceTimer.Enabled = true;
            serviceTimer.Start();
        }
        protected override void OnStart(string[] args)
        {

            if (!File.Exists(fileLocation))
                File.Create(fileLocation).Close();
            File.AppendAllText(fileLocation, "Service started : " + DateTime.Now.ToString() + Environment.NewLine);
        }

        void serviceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (isScheduleMatched())
                File.AppendAllText(fileLocation, "Service running at : " + DateTime.Now.ToString() + Environment.NewLine);
        }

        bool isScheduleMatched()
        {
            string[] arySchedule = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "\\Schedule.txt");
            string[] aryHours = arySchedule[0].Split(new char[] { ',' });
            string[] aryMinutes = arySchedule[0].Split(new char[] { ',' });
            int hours = DateTime.Now.Hour;
            int minutes = DateTime.Now.Minute;

            if (aryHours.Contains(hours.ToString()) && aryMinutes.Contains(minutes.ToString()))
                return true;
            else
                return false;
        }

        protected override void OnStop()
        {
            serviceTimer.Stop();
            serviceTimer.Enabled = false;
            File.AppendAllText(fileLocation, "Service stoped : " + DateTime.Now.ToString() + Environment.NewLine);
        }
    }
}

Output:





comments powered by Disqus


Search dotnetlearners.com