How set timer in worker thread

drjackool 956 Reputation points
2021-09-16T16:42:11.357+00:00

Hi
In Win32 app/MFC
Is there a way to set a timer like SetTimer() function for a window but for a working thread that not have a window?

Thanks

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,422 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 40,286 Reputation points
    2021-09-16T19:04:15.373+00:00

    You an use SetTimer in an MFC worker thread but it must have a message pump even though it doesn't create windows. For example -

    #pragma once
    
    // CTimerThread
    
    class CTimerThread : public CWinThread
    {
        DECLARE_DYNCREATE(CTimerThread)
    
    protected:
        CTimerThread();           // protected constructor used by dynamic creation
        virtual ~CTimerThread();
    
    public:
        virtual BOOL InitInstance();
        virtual int ExitInstance();
        static VOID CALLBACK TimerProc(HWND hwnd, UINT msg, UINT_PTR uintId, DWORD dwTime);
    protected:
        DECLARE_MESSAGE_MAP()
    public:
        UINT_PTR m_TimerId;
        DWORD m_Interval;
    };
    

    Implementation -

    // CTimerThread.cpp : implementation file
    //
    
    #include "pch.h"
    #include "CTimerThread.h"
    
    
    // CTimerThread
    
    IMPLEMENT_DYNCREATE(CTimerThread, CWinThread)
    
    VOID CALLBACK CTimerThread::TimerProc(HWND hwnd, UINT msg, UINT_PTR uintId, DWORD dwTime)
    {
        TRACE(_T("In %s\n"), _T(__FUNCTION__));
    }
    
    CTimerThread::CTimerThread()
    {
        m_TimerId = 0;
        m_Interval = 1000;
    }
    
    CTimerThread::~CTimerThread()
    {
    }
    
    BOOL CTimerThread::InitInstance()
    {
        // TODO:  perform and per-thread initialization here
        m_TimerId = SetTimer(NULL, 0, m_Interval, CTimerThread::TimerProc);
        return TRUE;
    }
    
    int CTimerThread::ExitInstance()
    {
        // TODO:  perform any per-thread cleanup here
        ASSERT(KillTimer(NULL, m_TimerId));
        return CWinThread::ExitInstance();
    }
    
    BEGIN_MESSAGE_MAP(CTimerThread, CWinThread)
    END_MESSAGE_MAP()
    
    
    // CTimerThread message handlers
    

    Start and stop the thread from an MFC dialog based application -

    void CMFCWorkTimerDlg::OnBnClickedStart()
    {
        // TODO: Add your control notification handler code here
        m_pTimerThread = AfxBeginThread(RUNTIME_CLASS(CTimerThread));
    }
    
    
    void CMFCWorkTimerDlg::OnBnClickedStop()
    {
        // TODO: Add your control notification handler code here
        PostThreadMessage(m_pTimerThread->m_nThreadID, WM_QUIT, 0, 0);
    }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful