Solved

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

Posted on 2013-05-29
4
443 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

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…
As more and more people are shifting to the latest .Net frameworks, the windows presentation framework is gaining importance by the day. Many people are now turning to WPF controls to provide a rich user experience. I have been using WPF controls fo…
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 demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

708 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now