That depends on whether your plugin is written in a procedural or object oriented style.
register_activation_hook
is what you want. https://codex.wordpress.org/Function_Reference/register_activation_hook
How exactly you incorporate it depends on your plugin coding style. Examples listed in the Codex show multiple approaches.
Procedural example:
If you have a function called myplugin_activate() in the main plugin file at either:
wp-content/plugins/myplugin.php or
wp-content/plugins/myplugin/myplugin.php
use this code:
function myplugin_activate() {
// Activation code here...
}
register_activation_hook( __FILE__, 'myplugin_activate' );
f your plugin uses the singleton class pattern, add the activation hook like so:
class MyPlugin {
static function install() {
// do not generate any output here
}
}
register_activation_hook( __FILE__, array( 'MyPlugin', 'install' ) );
Don’t forget to include a companion deactivation hook, especially if you are setting cron jobs and performing other tasks that need clean-up if the plugin is deactivated or deleted.