Often times I want to run a service for some project I'm working on, and every time I create the process either as a Windows Service or a new console app. Most of the time I like using a console app over a Windows Service for my projects at home though, because I want the flexibilty of user input and easy debugging.

I got tired of rewriting the logic for the process, so I decided to write up a quick template for this very thing. Hopefully it's useful to someone out there!

https://github.com/cherubdown/ConsoleServiceTemplate

The minimum interval is 5 seconds, but it can be lower by simply changing the value of RunInterval.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;

namespace ConsoleServiceTemplate
{
    class Program
    {
        public static int RunInterval = 5000;   // default to 5 seconds

        static void Main(string[] args)
        {
            AcceptArgs();   //ask for time input
            StartTimers();  //start the timers and kickoff Process
            Process();      //first process kickoff at T=0
            Wait();
        }

        /// 
        /// Awaits input for process runtime, with validation
        /// 
        private static void AcceptArgs()
        {
            Console.Write("Give interval between process run time (in ms, greater than 4999): ");
            string input = Console.ReadLine();
            Console.WriteLine();
            int value = RunInterval;
            if (input == null || input.Length < 0 || !int.TryParse(input, out value) || value < RunInterval)
            {
                Console.WriteLine("Input is not an integer greater than 4999.");
                AcceptArgs();
            }
            else
            {
                RunInterval = value;
            }
        }

        /// 
        /// Creates a timer and runs whatever is in Run
        /// 
        private static void StartTimers()
        {
            Console.WriteLine("Starting scanner.");
            Timer myTimer = new Timer();
            myTimer.Elapsed += Run;
            myTimer.Interval = RunInterval;
            myTimer.Enabled = true;
        }

        /// 
        /// While console is up, you can press ESC to stop
        /// 
        private static void Wait()
        {
            Console.WriteLine("Press ESC to stop.");
            do
            {
                while (!Console.KeyAvailable)
                {
                    // do nothing
                }
            } while (Console.ReadKey(true).Key != ConsoleKey.Escape);
        }

        /// 
        /// Process logic goes here
        /// 
        ///
        ///
        private static void Run(object src, ElapsedEventArgs e)
        {
            Process();
        }

        private static void Process()
        {
            Console.WriteLine("Process kickoff.");
        }
    }
}
Tags: tools