Код Windows C ++ (аналог CRON), который выполняет команду каждые хх часов - PullRequest
1 голос
/ 12 июня 2011

В ситуации, с которой я столкнулся, мне нужен код на C ++, который будет выполнять команду каждые 2 часа, хотя я не программирую на C ++ (скорее C #), но в этом случае я не могу использовать C #.

Может ли кто-нибудь предоставить пример кода, демонстрирующий это, пожалуйста

Ответы [ 3 ]

1 голос
/ 12 июня 2011

Возможно, что-то простое, как это?:

VOID WINAPI Sleep(
__in  DWORD dwMilliseconds
);

.

while (true)
{
   dosmt();
   sleep(2*60*60*1000);
}

Или запустить его в одном потоке на тот случай, если он должен выполняться параллельно оставшейся программе?В этом случае может помочь boost :: thread.

0 голосов
/ 12 июня 2011

Используйте мастер службы C ++, чтобы создать службу, и подключите ее к службе (конечно же, с дополнительным перехватом ошибок). Это должно работать с большинством современных версий Windows.

#include "stdafx.h"
#include <windows.h>
#include <iostream>
using namespace std;


/**
A callback function.  It is similar to a delegate in .Net.
*/
VOID CALLBACK theTimerCallback(PVOID aParam, BOOLEAN TimerOrWaitFired)
{
  // This is executed when the timer fires.
  cout << "The timer says: Hello, world." << endl;

  // The parameter (see below) is a handle to single the 
  // main thread to shut down.
  HANDLE theShutdownEvent = (HANDLE)aParam;

  // Tell the main thread to shutdown.
  SetEvent (theShutdownEvent);
}



int _tmain(int argc, _TCHAR* argv[])
{

  // Assuming you have a program running some main thread, this
  // will run a timer in the background and handle the timer callbacks.
  // So if this is a service, this timer would execute while the main
  // service thread can handle startup and shutdown of the service.

  // If it is just a single thread of an application that you manually
  // execute, then using a sleep in a loop would work fine.


  // Creating an event to make this main thread wait.
  HANDLE anEventHandle = CreateEvent (NULL, TRUE, FALSE, L"Shutdown event");


  // The queue object that handles the timers
  HANDLE theTimerQueueHandle = CreateTimerQueue ();


  HANDLE theTimerHandle = NULL; 

  if (CreateTimerQueueTimer (
    &theTimerHandle, // The handle to the timer is written to this variable.
    theTimerQueueHandle, // The handle to the timer queue that tracks this timer.
    theTimerCallback, // The callback function (see above).
    anEventHandle, // A parameter sent to the callback function.  This can be anything.
    10000, // Time to fire, in milliseconds (10 secs).
    0, // Execution period - 0 means it only fires once.
    WT_EXECUTEDEFAULT // Look at the API docs and pick your own flags.
    ) )
  {
    cout << "Main thread waiting for timer." << endl;
    // This makes the main thread wait until the timer fires.  Normally, something like
    // a service would have its own mechanism of waiting on the main thread.
    WaitForSingleObject (anEventHandle, INFINITE);


    // This shuts down all the timers, deletes their handles, waits for
    // handler functions to finish, and deletes the timer handles as well
    // as the queue handle.
    DeleteTimerQueueEx (theTimerQueueHandle, INVALID_HANDLE_VALUE);

  }

  CloseHandle (anEventHandle);

  cout << "Main thread exiting" << endl;
    return 0;
}
0 голосов
/ 12 июня 2011
Стандартные библиотеки

c ++ не предоставляют никакой опции, подобной таймерам c #, вы можете использовать sleep, но это приостановит поток,

Не очень точный обходной путь будет получать время от часов при инициализации,

и размещение проверки в некотором регулярно выполняемом блоке, чтобы увидеть, если время> init + шаг, а затем перейти к вашим инструкциям таймера и сбросить init = cur_time ..

или вы можете использовать таймер Windows:

http://www.cplusplus.com/forum/beginner/11271/ http://www.cplusplus.com/forum/windows/5531/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...