How can an extension run some code on its own installation or upgrading?

Place your extension installation / upgrading code into the Setup subfolder.
See for example the Magento_Customer module: https://github.com/magento/magento2/tree/develop/app/code/Magento/Customer/Setup

There are 5 script types: InstallSchema, UpgradeSchema, Recurring, InstallData, UpgradeData