Solved

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

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Windows Drag & Drop Location 2 94
TFS Branching 4 70
Need to create an object factory 2 44
Microsoft C++ code failing in executable that worked 9 82
zlib is a free compression library (a DLL) on which the popular gzip utility is built.  In this article, we'll see how to use the zlib functions to compress and decompress data in memory; that is, without needing to use a temporary file.  We'll be c…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
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…
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

943 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

6 Experts available now in Live!

Get 1:1 Help Now