> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Bulk Actions for an entire Player Segment

> Tutorial for creating a PlayFab task that runs one or more bulk actions, such as granting rewards, on every player in a target segment.

This tutorial walks you through the steps needed to create a task to perform one or more actions on every player in a segment.

Tasks are a vital part of live operations for any game. They give you a powerful set of tools for engaging with your players.

Examples might include:

* Give a special New Year’s gift to all players who logged in during the last 2 weeks.
* Reward players who spent money in the last week (based on spending tiers), where the more money they spent, the more valuable the gift.
* Fixing corrupted Player state for all players affected by a recent game bug.

In this tutorial, based on our **Unicorn Battle Sample App**, we will grant a special gift to all players with more than **2,725 XP**.

## Prerequisites

You will need to install the Unicorn Battle Sample App to run this tutorial. You can read more about it [in our blog](https://blog.playfab.com/blog/check-out-unicorn-battle), or go directly to the [GitHub repository](https://github.com/PlayFab/UnicornBattle) and follow the instructions there.

<img src="https://mintcdn.com/microsoft-4404708b/YzmQFdAfhA-NTCPa/images/playfab/data-analytics/acting-data/tutorials/unicorn-battle-launch-screen.webp?fit=max&auto=format&n=YzmQFdAfhA-NTCPa&q=85&s=682e9a99bb6293229a452095255ce2f2" alt="Unicorn Battle - Launch Screen" width="2560" height="1440" data-path="images/playfab/data-analytics/acting-data/tutorials/unicorn-battle-launch-screen.webp" />

You will want to play *several* battles, in order to level up your character to at least **Level 2**, which you reach at **2,725 XP** points.

<img src="https://mintcdn.com/microsoft-4404708b/YzmQFdAfhA-NTCPa/images/playfab/data-analytics/acting-data/tutorials/unicorn-battle-level-two.webp?fit=max&auto=format&n=YzmQFdAfhA-NTCPa&q=85&s=0f47eb0af3bb618e2aa449df163305f0" alt="Unicorn Battle - Level 2" width="2560" height="1440" data-path="images/playfab/data-analytics/acting-data/tutorials/unicorn-battle-level-two.webp" />

## Step 1 - Create the segment

The first step is to create the segment that defines the group of players who will be affected by this action. In this case, we need to create the **High XP Segment**, defined as all players who have more than **2,725 XP**:

* Select **PlayStream** from the menu on the left.
* Choose the **Segments** tab.
* Then select the **New Segment** button.
* Make the **Segment Name**: **High XP Players**.
* Define it as **Player**, where the **Statistic Value** called **Total\_XP Gained** is greater than **2725**.

<Note>
  **NOTE:** The current scheduled task system can process 10-15 tasks per second per segment. When designing your segments plan ahead for how large they will be and how long the task execution will run. There is no limit for how long a task can run but if they task needs to be executed in a specific timeframe then the segment needs to be sized properly.
</Note>

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-segments-high-xp-players.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=277244d7f9813aa8821acc626b4a903a" alt="Game Manager - PlayStream - Segments - High XP Players" width="1394" height="817" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-segments-high-xp-players.png" />

## Step 2 - Create a task for this segment

* Select the **Segments** tab.
* Then select **RUN TASK …**

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-segments-run-task.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=82870774c3122881a0419e880078401d" alt="Game Manager - PlayStream - Segments - Run Task" width="902" height="598" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-segments-run-task.png" />

This will take you to the **Create Task** view in the **Servers**->**Tasks** tab, and will pre-populate various fields based on your selected segment.

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-task-create-task.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=155bf1e0a504d077fc5aeea920791f65" alt="Game Manager - Servers - Task - Create Task" width="1280" height="900" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-task-create-task.png" />

## Step 3 - Add actions to the task

Next, you can finish setting up the task.

* Change the name to **Reward High XP Players**
* Add this description: **Give a gift to Players who are level 2 or higher**.
* Select **ADD ACTION**
  * Type in **Grant virtual currency** in the field provided.
  * **Virtual Currency** code: **GM** (short for **Gems**).
  * Amount: **20**
* Leave the scheduling set to **Manually** for now.
* Select the **SAVE AND RUN** button to run the task.

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-task-add-action-save-and-run.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=88be2126823b5296a972acebe78fb0e8" alt="Game Manager - Servers - Task - Add Action - Save and Run" width="1280" height="900" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-task-add-action-save-and-run.png" />

## Step 4 - Monitor your task

The **Tasks** view will show you your running task. Initially the task status will be **InProgress**, but it will quickly change to **Succeeded**, since the segment is small.

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-tasks-task-succeeded.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=f947e3bac92c4b78e3dd01f55d9a1ca3" alt="Game Manager - Servers - Tasks - Task Succeeded" width="1280" height="720" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-tasks-task-succeeded.png" />

Now, let's check out the task execution detail. Select the completed task in the previously run **Tasks** list. You will see important information, such as:

* How many players were processed.
* When the task started.
* How long it took to complete.
* The parameters it had when it was launched.
* Who ran it.
* If it was scheduled manually, etc.

If the task is still in progress, you can check the **Task Instance Detail** view for the progress, and see the estimated time remaining.

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-tasks-task-instance-details.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=6a29866408f6240c680cc1a48d0d0130" alt="Game Manager - Servers - Tasks - Task Instance Details" width="1280" height="900" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-tasks-task-instance-details.png" />

To verify that the task ran successfully:

* Navigate to the **Players** tab.
* Select your **Player**.
* Then choose the **Event History** tab.
* The most recent event in the list should be a **player\_virtual\_currency\_balance\_changed**, which should show your **Player’s** gems increasing by **20**.

<Note>
  You can expand this event to see the details.
</Note>

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-event-history-event-detail.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=8f5be92d094f953e458edc23c05339b9" alt="Game Manager - Event History - Event Detail" width="1458" height="622" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-event-history-event-detail.png" />

## What’s next

This tutorial has introduced you to the steps involved in performing an action for every player in a segment, but there’s a lot more you can do with tasks.

Here are a few ideas for other things you can try...

### Schedule your tasks

You don’t need to run tasks manually - you can schedule a task to run *automatically* on a *recurring* basis. For example, you could create a segment of all players who played the game in the last 24 hours, then run a scheduled tasks each day to give those players an XP boost.

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-segments-players-in-24-hours.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=011c1636bdcf356fef0958937679cdb6" alt="Game Manager - PlayStream - Segments - Players in 24 hours" width="780" height="815" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-segments-players-in-24-hours.png" />

<img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-tasks-scheduled-task.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=b818b7055457a8d9e13d6128d9e0e31b" alt="Game Manager - Servers - Tasks - Scheduled Task" width="1280" height="900" data-path="images/playfab/data-analytics/acting-data/tutorials/game-manager-servers-tasks-scheduled-task.png" />

### Run CloudScript for each player

The most powerful use of bulk actions is running an arbitrary CloudScript function for each player. This CloudScript can do anything the PlayFab server API can do - grant items, currency, inspect and change player data, and so on.

For example, imagine you have an event leaderboard that resets every week, and you want to go through all players and give a reward based on the value of the *last* event before it reset. The example provided below is using **Unicorn Battle**.

1. Create a new stat **Event\_QuestsCompleted**, that resets weekly and uses the aggregation method **Last**.

   <img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/players-leaderboards-edit-leaderboard.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=dc418906c884b0c685d0a4d05393dd7a" alt="Players - Leaderboards - Edit Leaderboard" width="571" height="541" data-path="images/playfab/data-analytics/acting-data/tutorials/players-leaderboards-edit-leaderboard.png" />

2. Create a new PlayStream action that increments this `Event_QuestsCompleted` stat, whenever `Total_QuestsCompleted` is changed.

   <img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/playstream-event-actions-edit-event-action.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=7f0d65c83146783af200454981eec9c6" alt="PlayStream - Event Actions - Edit Event Action" width="1043" height="943" data-path="images/playfab/data-analytics/acting-data/tutorials/playstream-event-actions-edit-event-action.png" />

3. Write a CloudScript function to be called by a Bulk Action task, which will go through players and give rewards based on the last value.

```javascript theme={null}
// this function will be called as a bulk action by a scheduled task for players in a segment
handlers.GiveTieredReward = function (args, context) {
    var profile = context.playerProfile;

    var statVersion = 0;        // set to whatever version you need to use

    var getStatRequest = {};
    getStatRequest.PlayFabId = profile.PlayerId;
    getStatRequest.StatisticNameVersions = [{ "StatisticName": "Event_QuestsCompleted", "Version": statVersion }];

    try {
        getStatRequest.PlayerResult = server.GetPlayerStatistics(getStatRequest);
    } catch (e) {
    };

    if (getStatRequest.PlayerResult && getStatRequest.PlayerResult.Statistics.length > 0) {
        getStatRequest.lastScore = getStatRequest.PlayerResult.Statistics[0].Value
    }

    if (getStatRequest.lastScore && getStatRequest.lastScore > 2) {
        // give gift to all players with more than 2 quests completed in last event
        // in a real event we would want to use a lookup table of gifts
        // but here we are just hard-coding it
        var giftRequest = {};
        giftRequest.PlayFabId = profile.PlayerId;
        giftRequest.ItemIds = ["CrystalKey"];
        giftRequest.grantResult = server.GrantItemsToUser(giftRequest);
        return giftRequest;
    } else {
        return getStatRequest;
    }
}
```

4. Set the new CloudScript version to **Live**, and create a new task that calls the `GiveTieredReward` function for all players. Don't forget to **Save** and **Run** the task.

   <img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/servers-tasks-new-scheduled-task.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=984b0ca050712fd0ad357ed1aa8365dd" alt="Servers - Tasks - New Scheduled Task" width="1280" height="900" data-path="images/playfab/data-analytics/acting-data/tutorials/servers-tasks-new-scheduled-task.png" />

5. You should notice events from this task appear in the PlayStream event debugger.

   <img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/playstream-dashboard-event-debugger.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=aed7ba302609d3de83967a15e6ffaff4" alt="PlayStream - Dashboard - Event Debugger" width="3079" height="1050" data-path="images/playfab/data-analytics/acting-data/tutorials/playstream-dashboard-event-debugger.png" />

6. You can select any player triggered action executed CloudScript event (by selecting the time stamp), and see the detailed result of CloudScript execution for each player. This includes useful diagnostic information such as the snapshot of the player profile at the time of the CloudScript execution.

   <img src="https://mintcdn.com/microsoft-4404708b/IwSYTY5BEqd_x-HK/images/playfab/data-analytics/acting-data/tutorials/playstream-dashboard-raw-event-json.png?fit=max&auto=format&n=IwSYTY5BEqd_x-HK&q=85&s=02ea8cca957596e793448dfa583d7c0c" alt="PlayStream - Dashboard - Raw Event JSON" width="1464" height="1923" data-path="images/playfab/data-analytics/acting-data/tutorials/playstream-dashboard-raw-event-json.png" />


## Related topics

- [Player Segments](/services/playfab/player-progression/player-data/player-segments.md)
- [PlayFab Live service management documentation](/services/playfab/live-service-management/index.md)
- [Player Segment configuration](/services/playfab/player-progression/player-data/player-segment-configuration.md)
- [Economy V2 Segment Actions](/services/playfab/economy-monetization/economy-v2/player-segmented-monetization/segment-actions.md)
- [Segment Configuration](/services/playfab/live-service-management/game-configuration/segmentation/segmentation-configuration.md)
