Instance lifecycle hooks

更新时间: 2026-04-18 06:10:20

This topic describes how to implement and use instance lifecycle hooks in a PHP runtime.

Background

When you implement and configure an instance lifecycle hook, Function Compute invokes the corresponding hook when a specific lifecycle event occurs. The PHP runtime supports two instance lifecycle hooks: Initializer and PreStop. For more information, see Configure instance lifecycles.

The billing rules for an instance lifecycle hook are the same as those for a regular request invocation. However, you can query its execution logs only in Real-time Logs, Function Logs, or Advanced Logs. The invocation request list does not display logs for these hooks. For more information, see View instance lifecycle hook logs.

Initializer hook

Initializer example

The Initializer hook runs after a function instance starts but before its handler is executed. Function Compute ensures that the Initializer hook is successfully executed at most once within the lifecycle of a function instance. If the Initializer hook fails on its first attempt, the function invocation fails immediately. On the next invocation, a new function instance is created and the hook runs again.

Note

When an Initializer hook times out or fails, the server always returns an HTTP 200 status code. You must check the X-Fc-Error-Type:InitializationError response header or the errorMessage field in the response body to determine if the error was caused by an initialization failure.

The Initializer hook accepts a single input parameter, $context, which is identical to the context parameter in a handler.

The following is a minimal Initializer hook.

<?php
function my_initializer($context) {
    $logger = $GLOBALS['fcLogger'];
    $logger->info("hello world");
}
?>            

my_initializer is the name of the Initializer hook method. This name must match the value you set for the Initializer Hook in the Function Compute console. For example, if you configure the Initializer Hook as main.my_initializer for your function, Function Compute loads and runs the my_initializer method defined in the main.php file.

Method signature

  • The hook accepts a single input parameter, context, which is identical to the handler's context object.

  • The initializer and initializationTimeout fields within the context object are designed for the Initializer hook. If you use the Initializer feature, these fields are set to the values of the Initializer Hook and Initializer Hook Timeout Period that you configure for the function. Otherwise, these fields are empty and ignored.

  • The hook has no return value.

PreStop hook

The PreStop hook runs before a function instance is destroyed. It has the same method signature as the Initializer hook.

The following is an example of a PreStop hook.

<?php

$counter = 0;
function preStop($context) {
    $GLOBALS['fcLogger']->info("preStop ok");
}

function handler($event, $context) {
    global $counter;
    $counter += 2;
    return $counter;
}
?>

You can query logs for the PreStop hook in the Logstore configured for your function. For example, use the following query statement to find all logs for the function. For more information, see Query logs related to hooks.

<funcName> AND <ServiceName> AND qualifier: <VERSION>

Configure lifecycle hooks

Configure in the console

In the Function Compute console, you can configure the Initializer Hook and PreStop Hook for an FC function in the Configuration > Instance Configuration section. For more information, see Configure instance lifecycle. The callback format is [file_name.method_name], for example:

  • Set Initializer Hook to index.initialize to call the initialize method in the index.php file.

  • Set PreStop Hook to index.preStop to call the preStop method in the index.php file.

Configure by using Serverless Devs

If you use Serverless Devs, add the configurations for the Initializer Hook and PreStop Hook to your s.yaml file.

  • Initializer hook configuration

    In the function configuration, add the instanceLifecycleConfig.initializer field, which includes the handler and timeout fields.

  • PreStop hook configuration

    Add the instanceLifecycleConfig.preStop field, which contains the handler and timeout fields, to the function configuration.

The following code provides a configuration example.

edition: 3.0.0
name: fcDeployApp
access: "default"

vars: # Global variables
  region: "cn-hangzhou"

resources:
  hello_world:
    component: fc3 # Component name
    props:
      region: ${vars.region}              # For more information about how to use variables, see: https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC
      functionName: "testphp"
      description: 'this is a test'
      runtime: "php7.2"
      code: ./
      handler: index.handler
      memorySize: 128
      timeout: 30
      instanceLifecycleConfig:      # Instance lifecycle hooks
        initializer:                # Initializer hook
          handler: index.my_initializer 
          timeout: 60     
        preStop:                    # PreStop hook
          handler: index.preStop    # Function handler
          timeout: 60               # Timeout
 

For more information about the YAML configuration specifications for Serverless Devs, see Common commands of Serverless Devs.

View the logs of instance lifecycle hooks

You can view the logs for lifecycle hook in Logs.

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Test Function tab, click Test Function, and then choose Logs > Function Logs.

    On the Logs tab, you can view function invocation logs and Initializer logs. Example:

    2024-03-04 17:57:28FC Initialize Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69
    2024-03-04 17:57:282024-03-04 09:57:28.192 1-65e59b07-1520da26-bf73bbb91b69 [info] initializer
    2024-03-04 17:57:28FC Initialize End RequestId: 1-65e59b07-1520da26-bf73bbb91b69
    2024-03-04 17:57:28FC Invoke Start RequestId: 1-65e59b07-1520da26-bf73bbb91b69
    2024-03-04 17:57:28FC Invoke End RequestId: 1-65e59b07-1520da26-bf73bbb91b69

    Each function instance is cached for a period of time and not immediately destroyed, you cannot view logs for PreStop hooks right away. To quickly trigger a PreStop hook, you can update the function configurations or function code. After the update is complete, you can view the logs for PreStop hooks in Function Logs. The following sample code shows an example:

    2024-03-04 18:33:26FC PreStop Start RequestId: 93c93603-9fbe-4576-9458-193c8b213031
    2024-03-04 18:33:262024-03-04 10:33:26.077 93c93603-9fbe-4576-9458-193c8b213031 [info] preStop
    2024-03-04 18:33:26FC PreStop End RequestId: 93c93603-9fbe-4576-9458-193c8b213031

Example program

Function Compute provides a MySQL sample project that uses the Initializer and PreStop hooks. In this sample, the Initializer hook reads the MySQL database configuration from environment variables, creates a MySQL connection, and tests its connectivity. The PreStop hook closes the MySQL connection. For more information, see php72-mysql.

上一篇: Error handling 下一篇: Java
阿里云首页 函数计算 相关技术圈