Yordan Yanakiev
Yordan Yanakiev

Reputation: 2604

Service started and then stopped?

procedure TService1.ServiceExecute(Sender: TService);
var
   FileName : string;
   Strm     : TMemoryStream;
   i        : integer;
   h,m,s,ms : word;
begin

   DecodeTime( now, h, m, s, ms );

   if ( h = 13 ) AND ( m = 6 ) AND ( s = 0 ) then
   begin
      ShowMessage( 'entered' );
      for i := 0 to 3 do
      begin

         DateTimeToString( FileName, 'yyyy-mm-dd-hh-nn-ss', now );

         FileName := ExtractFilePath( Application.ExeName ) + FileName + '.jpg';

         if not FileExists( FileName ) then
         begin
            try

               Strm := TMemoryStream.Create;

               try
                  IdHTTP_ := TIdHTTP.Create( nil );

                  try
                     IdHTTP_.Get( 'http://192.168.1.223/snapshot/view0.jpg', Strm );
                  finally
                     IdHTTP_.Free;
                  end;

                  Strm.Position := 0;
                  Strm.SaveToFile( FileName );

               finally
                  Strm.Free;
               end;

            except

            end;
         end;

         Sleep( 5000 );

      end;

   end;
end;

this is my code for a service which is supposed to took 4 snapshots from an IP Camera in specific time. Anyway as soon as I start the service, i am receiving the message "The Service1 service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.", and the service is terminated.

Upvotes: 0

Views: 1666

Answers (1)

David Heffernan
David Heffernan

Reputation: 613013

The documentation for OnExecute says:

Occurs when the thread associated with the service starts up.

If you are not spawning a new thread to handle individual service requests in an OnStart event handler, this is where you implement the service. When the OnExecute event handler finishes, the service thread terminates. Most OnExecute event handlers contain a loop that calls the service thread's ProcessRequests method so that other service requests are not locked out.

Your OnExecute does not loop. Once that function exits, the service stops. You will need to do what the documentation describes. Either loop, or spawn a thread to handle service requests.

Do be aware that you cannot show UI in a service. So your attempts to call ShowMessage cannot work. You'll need to use a logging mechanism appropriate for services. For example one that writes to a file.

What you are trying to do would be much easier in a normal desktop process which was scheduled as a scheduled task. I think a service is the wrong solution to your problem.

Upvotes: 10

Related Questions