---
id: actor-lifecycle
title: Actor lifecycle
---

import CodeBlock from '@theme/CodeBlock';

import InitExitExample from '!!raw-loader!./code/01_init_exit.py';
import ContextManagerExample from '!!raw-loader!./code/01_context_manager.py';
import RebootExample from '!!raw-loader!./code/01_reboot.py';
import StatusMessageExample from '!!raw-loader!./code/01_status_message.py';

In this guide, we will show you how to manage the lifecycle of an Apify Actor.

## Initialization and cleanup

At the start of its runtime, the Actor needs to initialize itself, its event manager and its storages, and at the end of the runtime it needs to close these cleanly. The Apify SDK provides several options on how to manage this.

The [`Actor.init`](../../reference/class/Actor#init) method initializes the Actor, the event manager which processes the Actor events from the platform event websocket, and the storage client used in the execution environment. It should be called before performing any other Actor operations.

The [`Actor.exit`](../../reference/class/Actor#exit) method then exits the Actor cleanly, tearing down the event manager and the storage client. There is also the [`Actor.fail`](../../reference/class/Actor#fail) method, which exits the Actor while marking it as failed.

<CodeBlock className="language-python">
    {InitExitExample}
</CodeBlock>

### Context manager

So that you don't have to call the lifecycle methods manually, the [`Actor`](../../reference/class/Actor) class provides a context manager, which calls the [`Actor.init`](../../reference/class/Actor#init) method on enter, the [`Actor.exit`](../../reference/class/Actor#exit) method on a clean exit, and the [`Actor.fail`](../../reference/class/Actor#fail) method when there is an exception during the run of the Actor.

This is the recommended way to work with the `Actor` class.

<CodeBlock className="language-python">
    {ContextManagerExample}
</CodeBlock>

## Rebooting an Actor

Sometimes, you want to restart your Actor to make it run from the beginning again. To do that, you can use the [`Actor.reboot`](../../reference/class/Actor#reboot) method. When you call it, the Apify platform stops the container of the run, and starts a new container of the same Actor with the same run ID and storages.

Don't do it unconditionally, or you might get the Actor in a reboot loop.

<CodeBlock className="language-python">
    {RebootExample}
</CodeBlock>

## Actor status message

To inform you or the users running your Actors about the progress of their runs, you can set the status message for the run, which will then be visible in the run detail in Apify Console, or accessible through the Apify API.

To set the status message for the Actor run, you can use the [`Actor.set_status_message`](../../reference/class/Actor#set_status_message) method.

<CodeBlock className="language-python">
    {StatusMessageExample}
</CodeBlock>
