2

I created a program that runs every day at 5:00 p.m. but when I debug the program the console always stays open I want to debug once is close my pc and demin when I open my pc without running the program another time the application runs at 5:00 pm automatically

var DailyTime = "5:00:00";
var timeParts = DailyTime.Split(new char[1] { ':' });

while (true)
{
    var dateNow = DateTime.Now;
    var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
    int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
    TimeSpan ts;

    if (date > dateNow)
        ts = date - dateNow;
    else
    {
        date = date.AddDays(1);
        ts = date - dateNow;
    }

    Task.Delay(ts).Wait();
    Copie();
    FichierTrace.Close();
    Console.Read();
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
sara
  • 21
  • 2
  • Have a look at [this](https://stackoverflow.com/questions/3243348/how-to-call-a-method-daily-at-specific-time-in-c). It might help you. – instanceof Oct 09 '20 at 07:38
  • I tried that but when I run the program the console stays open I don't want that what I want is even I shut down my pc and the next day it turned on without making another execution at 5:00 the program will run by itself – sara Oct 09 '20 at 07:46
  • it's not a Winforms application it's a console application without form – sara Oct 09 '20 at 07:50
  • 1
    It stays open, because you need an input to `Console.Read()`. Remove that line and it will close automatically. You also have an infinite loop => will stay open. Remove all the timing code, which doesn't work anyway. Then use Windows Task Scheduler to execute it according to schedule. – Fildor Oct 09 '20 at 07:50
  • 4
    Everything after _"...always stays open..."_ makes no sense to me. It's probably staying open due to the endless loop caused by `while (true)` with no sign of return/break –  Oct 09 '20 at 08:04

1 Answers1

2

I have two possible solutions for you, but first, you must do the following either way:

  1. Throw away all the "timing" code.
  2. Throw away the infinite loop 'while(true)...`
  3. Boil it down to the task that should be done and nothing else.

Then you can either:

  1. Use Windows Task Scheduler and setup a trigger to execute the program each day at 5:00 PM

Or

  1. Write a Windows Service around it, that you register to be started automatically on boot. That service then uses some scheduling framework like for example Quartz1 to schedule a job that will perform the actual Task.

If you think about it you will probably find that 1.) is much easier to do. 2.) Gives you different options but I think plain console program and Windows Scheduler should be sufficient here. And you can still evolve it later on.

Footnotes

1 I am not affiliated with the Quartz.NET project. It's just the one I happen to know.

Fildor
  • 14,510
  • 4
  • 35
  • 67