Julian Huxley
Julian Huxley

Reputation:

Win32 function for scheduled tasks in C++

I have a function in C++ that needs to be called after a period of time and this task is repeated. Do you know any built-in function or sample code in Win32 or pthread?

Thanks,

Julian

Upvotes: 2

Views: 1489

Answers (3)

Software_Designer
Software_Designer

Reputation: 8587

SetTimer!

An example:

  #include <windows.h>
  #include <stdio.h>

  void CALLBACK scheduled_task_1 (HWND hwnd, UINT msg, UINT id, DWORD time) 
  {
      puts("Executing  scheduled_task_1 every half-second event");
  }

  void CALLBACK scheduled_task_2 (HWND hwnd, UINT msg, UINT id, DWORD time) 
  {
      puts("Executing  scheduled_task_2 every two seconds event");
  }

  void CALLBACK scheduled_task_3 (HWND hwnd, UINT msg, UINT id, DWORD time) 
  {
      puts("Executing  scheduled_task_3 24 hours event");

  }

  void messageLoop(void) {
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) > 0)
      DispatchMessage( &msg );
  }

  int main(void) 
  {
    while(true)
    {
        SetTimer (NULL, 0,   500, scheduled_task_1);  /* every half-second */
        SetTimer (NULL, 0,  2000, scheduled_task_2);  /* every two seconds */
        SetTimer (NULL, 0, 60*60*24*1000, scheduled_task_3); /* after 24 hours or 86400000 milliseconds */
        messageLoop();
    }
    return 0;
  }

Upvotes: 0

brad
brad

Reputation: 2249

Just as a side note, I hope that you aren't doing something in code which could be done via the OS. (I don't know enough about your requirements to say, but I thought I'd point it out).

Things such as task-scheduler (windows) are made for scheduling recurring tasks, and they often do a better job than hand-rolled solutions.

Upvotes: 1

Eric Petroelje
Eric Petroelje

Reputation: 60498

How about SetTimer.

  1. Create a wrapper function to use as the callback for set timer.
  2. Wrapper function calls your function.
  3. After your function finishes, wrapper function calls SetTimer again to re-set the timer.

Upvotes: 5

Related Questions