Invoke a Service
In this section we create a new algorithm, SecondAlg, in which the FirstSvc is invoked.
The header file is,
// file SecondAlg.h
#ifndef SECOND_ALG_H
#define SECOND_ALG_H
#include "SniperKernel/AlgBase.h"
class IfMySvc;
class SecondAlg : public AlgBase
{
public:
SecondAlg(const std::string& name);
bool initialize();
bool execute();
bool finalize();
private:
unsigned int m_count;
IfMySvc* m_svc;
};
#endif
And the source file is,
// file SecondAlg.cc
#include "SecondAlg.h"
#include "FirstSvc/IfMySvc.h"
#include "SniperKernel/AlgFactory.h"
DECLARE_ALGORITHM(SecondAlg);
SecondAlg::SecondAlg(const std::string& name)
: AlgBase(name),
m_count(0)
{
}
bool SecondAlg::initialize()
{
LogDebug << "in the SecondAlg::initialize()" << std::endl;
SniperPtr<IfMySvc> _svc(this->getScope(), "MyService");
if ( _svc.valid() ) {
LogInfo << "the IfMySvc instance is retrieved" << std::endl;
}
else{
LogError << "Failed to get the IfMySvc instance!" << std::endl;
return false;
}
m_svc = _svc.data();
return true;
}
bool SecondAlg::execute()
{
LogDebug << "in the SecondAlg::execute()" << std::endl;
++m_count;
LogInfo << "loop " << m_count << std::endl;
if ( m_count%2 == 1 ) {
m_svc->doSomeThing();
}
return true;
}
bool SecondAlg::finalize()
{
LogDebug << "in the SecondAlg::finalize()" << std::endl;
return true;
}
In order to avoid the retrieval of FirstSvc in each time of the events loop, we retrieve it in initialize()
, which is executed only once at the beginning of the application. A class template, SniperPtr, is used for the retrival. Then the raw pointer is assigned to the data member m_svc
.
- the template parameter can be the concrete type of the service (FirstSvc), or the pure virtual base class (IfMySvc). We use the later one for flexibility in this example.
- the 1st constructor parameter indicates where to find the service. In most situations it is
this->getScope()
. It might be different when we have multiple Task instances, which will be described as an advanced topic in later sections. - the 2nd constructor parameter indicates the name of the service instance;
During the event loop, the service is not always invoked. In this example, it's invoked only when the loop count is odd.