0

How can I set some data if today is the first day of the month, and where can I do this?

The code below gives me the first day of the month, but where should I use this?

DateTime now = DateTime.Now;
DateTime firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
if(now.Day == firstDayOfMonth)
{
  SOME CODE;
}

Important that the 'SOME CODE' was made only once a month

tereško
  • 58,060
  • 25
  • 98
  • 150
Wl0di
  • 33
  • 7
  • I think that you need to use a service that will check that or kind of scheduler. – billybob Jan 04 '16 at 17:12
  • Could you suggest me how I can do or where I can read about it? – Wl0di Jan 04 '16 at 17:14
  • 1
    Wouldn't it be easier to use `DateTime.Now.Day == 1` for the if? – Krisztián Balla Jan 04 '16 at 17:17
  • 1
    @JennyO'Reilly maybe so, but it is less important – Wl0di Jan 04 '16 at 17:20
  • What does the code do? Maybe it would make sense to put the code into a separate application and execute it only every first day of a month (using the Windows Task Scheduler for example). This would also help you to rerun the code in case of an error. – Krisztián Balla Jan 04 '16 at 17:20
  • Watch out for time zones – Zuzlx Jan 04 '16 at 17:27
  • 1
    I note that your code only solves the problem "I must ensure that the code runs only on the first of the month". It does not solve the problem you stated, which is that the code runs **only once a month**. If someone runs your code a million times and fifty thousand of them happen to be on the first of this month, then the code runs fifty thousand times in a month, not once in a month. You need to know not only whether this is the first of the month, but also whether the code has run already this month. – Eric Lippert Jan 04 '16 at 17:56

1 Answers1

1

Maybe you can use Quartz.NET. I'm using it in a windows service, but you can also bind it to MVC.

You can check this answer: Job Scheduler inside of MVC3 Website, to see how to implement it.

Community
  • 1
  • 1
billybob
  • 2,859
  • 6
  • 35
  • 55