Solved

How to make a Windows Service that deletes file every 15 minutes with C#?

Posted on 2013-05-29
4
467 Views
Last Modified: 2013-12-03
I can make a project with Windows Service option from Visual Studio, but I cannot figure out how I can make one that will delete file every 15 minute or 1 hour. Also how can I install that? My environment is C# .NET Windows  and Visual Studio 2010/2012. Please help.
0
Comment
Question by:ashley2009
  • 3
4 Comments
 
LVL 11

Expert Comment

by:wrmichael
ID: 39205687
You need to track a start date time and then check the difference between the current time in a loop until it is greater than so many minutes.  

then reset the start time with current time and go back to a loop again.

You will need to sleep your thread during the looping to make sure it doesn't eat your processor up between cycles.
0
 
LVL 11

Expert Comment

by:wrmichael
ID: 39205691
Here is some date math code I found that might help you.

DateTime startTime = DateTime.Now;

DateTime endTime = DateTime.Now.AddSeconds( 75 );

TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );

Open in new window

0
 
LVL 3

Author Comment

by:ashley2009
ID: 39206546
Hello,

actually I need a sample of the cs file that would show how I can call a method from a windows service cs file page. It does not have to be even delete file. Just a Windows service. I cannot figure out where to insert a method like "DeleteFile()" or "GetDataFromTable()". Should I insert a method, say that has to execute say every day or or every week at OnStart()? Would you please give me some code that shows where I will insert my method that will be executing say every day.
0
 
LVL 11

Accepted Solution

by:
wrmichael earned 500 total points
ID: 39210487
in general you create a class,  on the "onstart" you call a function that creates an instance of that class by using a thread and then you start the thread.   then loop with a sleep between your loops so you don't overload the processor with looping.

you stop that thread in the onStop.

Look at this example:

http://www.codeproject.com/Articles/3938/Creating-a-C-Service-Step-by-Step-Lesson-I

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;

namespace CodeBlooded.Spades.Services
{
    public class SpadesServiceBase : System.ServiceProcess.ServiceBase
    {
        public SpadesServiceBase() {
            // create a new timespan object
            // with a default of 10 seconds delay.
            m_delay = new TimeSpan(0, 0, 0, 10, 0 );
        }

        /// <SUMMARY>
        /// Set things in motion so your service can do its work.
        /// </SUMMARY>
        protected override void OnStart(string[] args) {
            // create our threadstart object to wrap our delegate method
            ThreadStart ts = new ThreadStart( this.ServiceMain );

            // create the manual reset event and
            // set it to an initial state of unsignaled
            m_shutdownEvent = new ManualResetEvent(false);

            // create the worker thread
            m_thread = new Thread( ts );

            // go ahead and start the worker thread
            m_thread.Start();

            // call the base class so it has a chance
            // to perform any work it needs to
            base.OnStart( args );
        }
 
        /// <SUMMARY>
        /// Stop this service.
        /// </SUMMARY>
        protected override void OnStop() {
            // signal the event to shutdown
            m_shutdownEvent.Set();

            // wait for the thread to stop giving it 10 seconds
            m_thread.Join(10000);

            // call the base class 
            base.OnStop();
        }

        /// <SUMMARY>
        /// 
        /// </SUMMARY>
        protected void ServiceMain() {
            bool        bSignaled    = false;
            int            nReturnCode    = 0;
            
            while( true ) {
                // wait for the event to be signaled
                // or for the configured delay
                bSignaled = m_shutdownEvent.WaitOne( m_delay, true );

                // if we were signaled to shutdow, exit the loop
                if( bSignaled == true )
                    break;

                // let's do some work
                nReturnCode = Execute();
            }
        }

        /// <SUMMARY>
        /// 
        /// </SUMMARY>
        /// <RETURNS></RETURNS>
        protected virtual int Execute() {
            return -1;
        }

        protected Thread            m_thread;
        protected ManualResetEvent    m_shutdownEvent;
        protected TimeSpan            m_delay;
    }
}

Open in new window



Another method using workers is here:

http://code.msdn.microsoft.com/windowsdesktop/CSWindowsService-9f2f568e
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Problem updating Access table using VB code 8 55
Issue testing the Class Library 4 58
ODBC Connection; Switch between 2 SQL Databases VBA 11 103
Explain Unit of Work pattern 2 69
This article shows how to make a Windows 7 gadget that extends its U/I with a flyout panel -- a window that pops out next to the gadget.  The example gadget shows several additional techniques:  How to automatically resize a gadget or flyout panel t…
For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question