C# execute method every 5 seconds.

Atouray
Atouray used Ask the Experts™
on
I've a c# method that delete files older than 30 seconds. Now I need timer to execute/run this method every 5 seconds. How best can I achieve this? Also I need this application to run at startup
and continue running until shutdown.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Create window service application .

That is best solution if you want to run application in background.

In Window Service you can use System.Timers.Timer class for that purpose.
If you're using Windows.Forms, you can use a Windows.Forms.Timer. Otherwise, the best bet is probably a new thread with a 5 second sleep.
System.Windows.Forms.Timer timer;
this.timer = new System.Windows.Forms.Timer(this.components);
this.timer.Interval = 5000;
this.timer.Tick += new System.EventHandler(this.timer_Tick);
...
this.timer.Start();
...
private void timer_Tick(object sender, System.EventArgs e)
{
  // process file here
}

Open in new window

Marcus KeustermansSolutions Architect

Commented:
What you need here are 2 steps. The reason for this is that the file attributes can be altered and this can lead to a file not being deleted.

I would create 2 windows services and they should execute the following steps
The first service should implement a  filesystemwatcher with which I can log the creation times of the files probably to database, and the 2nd windows service will execute every 5 seconds query the database for any files older then 30 seconds, delete the files and the entries into the database.  If you want to keep a history on what was created and deleted then you can keep the entries in the database and just add the deletion time to the affected entries.
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Marcus KeustermansSolutions Architect

Commented:
By the way you could also implement both steps in one windows service if you whish to. I would prefer 2 as it would be possilble to run them individually and switch them off individualy. Eg you might want to log file creation and not delete files for a period of time.  2 services will allow you to switch of the deletion service and keep on logging.  With one servoce you would have to change your code to do that.

Author

Commented:
On my visual studio 2008 I cannot get the methodTick. I need the solution as  am very new to windows services. Even if it's not the whole solution but at least a startup.

Thanks.

Author

Commented:
I've been able to start and made some progress I started writing the service. I can now see Tick method after using the windows forms time from the toolbox. Now I need to know how to install the service and also have some configuration files for the end user.
Marcus KeustermansSolutions Architect
Commented:
Hi there you should be using the System.Timer timer and the elapsed event.
using System.Timers;
Timer deleteTimer = new Timer();
deleteTimer.Elapsed+=new ElapsedEventHandler(deleteTimer_Elapsed);

protected void deleteTimer_Elapsed(object sender, ElapsedEventArgs e)
 {
          //Delete files here.
}

After all Windows Forms controls belong on Windows Forms and not windows services as they have no visual component.

To instsall the service you need to firstly add a service installer class.  Once you compile your service you can install it using the installutil command in your visual studio command prompt: navigate to the folder where the executable is and then run the following command to install the service
'installutil /i MyService.exe'

to uninstall run command 'installutil /u MyService.exe.


[RunInstaller(true)]
    public class WindowsServiceInstaller : Installer
    {
        /// <summary>
        /// Public Constructor for WindowsServiceInstaller.
        /// - Put all of your Initialization code here.
        /// </summary>
        public WindowsServiceInstaller()
        {
            ServiceProcessInstaller serviceProcessInstaller =
                               new ServiceProcessInstaller();
            ServiceInstaller serviceInstaller = new ServiceInstaller();

            //# Service Account Information
            serviceProcessInstaller.Account = ServiceAccount.LocalSystem;        
            //# Service Information
            serviceInstaller.DisplayName = "My New C# Windows Service";
            serviceInstaller.StartType = ServiceStartMode.Automatic;

            //# This must be identical to the WindowsService.ServiceBase name
            //# set in the constructor of WindowsService.cs
            serviceInstaller.ServiceName = "My Windows Service";

            this.Installers.Add(serviceProcessInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }

Author

Commented:
Below is my code but it's not working installed the service successfully and started it successfully but the files are not deleted after 5 seconds. Am I missing something? The problem is the timer, if I place the delete code above the time whenever the script starts the files are deleted but the timer execution is not working.
namespace ImageCleaner
{
    public partial class imgCleaner : ServiceBase
    {
        private String pathImages = ConfigurationSettings.AppSettings["folderPath"];
        public imgCleaner()
        {
            InitializeComponent();
            Timer timer = new Timer();
            //CleanImageFolder("C:\\ImageCheck");
            timer.Interval = 5000;
            timer.Start();
            timer.Elapsed += new ElapsedEventHandler(this.timer_Tick);
            
        }
 
        protected override void OnStart(string[] args)
        {
        }
 
        protected override void OnStop()
        {
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            CleanImageFolder("C:\\ImageCheck");
        }
        
        private void CleanImageFolder(String imgPath)
        {
            string imgFolder = imgPath;
            string[] imgList = Directory.GetFiles(imgFolder, "*");
            foreach (string img in imgList)
            {
                FileInfo imgInfo = new FileInfo(img);
                if (imgInfo.LastWriteTime < DateTime.Now.AddSeconds(-30))
                {
                    imgInfo.Delete();
                }
            }
        }
        
    }
}

Open in new window

Commented:

 private String pathImages = ConfigurationSettings.AppSettings["folderPath"];
private bool processst = false;
        public imgCleaner()
        {
            InitializeComponent();
            Timer timer = new Timer();
            //CleanImageFolder("C:\\ImageCheck");
            timer.Interval = 5000;
            timer.Enable = true; 
            timer.Start();
            timer.Elapsed += new ElapsedEventHandler(this.timer_Tick);
            
        }
 
        protected override void OnStart(string[] args)
        {
        }
 
        protected override void OnStop()
        {
        }
        private void timer_Tick(object sender, EventArgs e)
        {
            if(!processst)
            {
            processst = true;
            CleanImageFolder("C:\\ImageCheck");
            processst = false; 
            }
        }
        
        private void CleanImageFolder(String imgPath)
        {
            string imgFolder = imgPath;
            string[] imgList = Directory.GetFiles(imgFolder, "*");
            foreach (string img in imgList)
            {
                FileInfo imgInfo = new FileInfo(img);
                if (imgInfo.LastWriteTime < DateTime.Now.AddSeconds(-30))
                {
                    imgInfo.Delete();
                }
            }
        }

Open in new window

Author

Commented:
Thanks a lot it's working now I need to be install to the client machine which has no visual studio otherwise I would have used installutil to install. Any ideas how to do this?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial